python异常处理

基础

问题出现

我们先来看一个小案例,我们希望用户输入手机号码,然后打印到前台,如下所示:

number = int(input("please enter your phone number:" ))
print(number)

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
please enter your phone number:15564105999
15564105999

但是如果用户不按套路出牌,胡乱输入,这个时候程序就可能崩溃,如下所示:

number = int(input("please enter your phone number:" ))
print(number)

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
please enter your phone number:kjdsfklsdgkgj
Traceback (most recent call last):
  File "G:\python2\test_1.py", line 1, in <module>
    number = int(input("please enter your phone number:" ))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'kjdsfklsdgkgj'

Process finished with exit code 1

问题分析

当然了,为了防止程序崩溃,我们除了加上判断之外,还可以通过python内置的异常处理机制进行处理,如下所示:

# 使用try和except结构,一旦type当中的代码遇到任何错误,程序都不会崩溃,而是会运行except当中的代码
try:
    number = int(input("please enter your phone number:" ))
    print(number)
except:
    print("invalid input")

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
please enter your phone number:kdjsfj
invalid input

Process finished with exit code 0

但这么做又有一个问题,except的的范围太大了,它不管try当中会遇到什么问题,只有遇到问题,它就会执行,这会导致我们看不到try代码当中真正的错误,如下所示,try代码当中有一个明确的错误,那就是value = 10/0,我们一执行出了错误之后except当中的代码立马就会执行!导致我们并不知道到底是value = 10/0出了错,还是number=……出了错,这样不好,不方便调试,主要原因就是except的所承包的错误范围太大了!那不能只让except只侦听特定的错误,比如只侦听number是否是整数呢?

try:
    value = 10/0
    number = int(input("please enter your phone number:" ))
    print(number)
except:
    print("invalid input")

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
invalid input

问题解决

# 先来看
value = 10/0

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
Traceback (most recent call last):
  File "G:\python2\test_1.py", line 1, in <module>
    value = 10/0
            ~~^~
ZeroDivisionError: division by zero  < 看这里面,报错的类型是与0相关的除法
# 再看
number = int(input("please enter your phone number:" ))
print(number)

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
please enter your phone number:kjdsfklsdgkgj
Traceback (most recent call last):
  File "G:\python2\test_1.py", line 1, in <module>
    number = int(input("please enter your phone number:" ))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10:   < 看这里面,报错的类型是值错误

Process finished with exit code 1

既然两种报错不一样,我们就可以利用except专门针对不同的报错类型进行报错,通过看报错,就能清楚的知道哪个地方有了错误,如下所示:

try:
    value = 10 / 0
    number = int(input("please enter your phone number:"))
    print(number)
except ZeroDivisionError:
    print("Divided by zero")
except ValueError:
    print("invalied input")

"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
Divided by zero <---一看这个错误,就知道是与0相关的错误,肯定是value = 10/0这一行有错误

Process finished with exit code 0
try:
    number = int(input("please enter your phone number:"))
    print(number)
    value = 10 / 0
except ZeroDivisionError:
    print("Divided by zero")
except ValueError:
    print("invalied input"
"C:\Program Files\Python311\python.exe" G:\python2\test_1.py 
please enter your phone number:dfdsdf
invalied input  <---一看这个错误,就知道是与值相关错误

Process finished with exit code 0

总结

通过try/except这种结构,让except接受特定的错误返回我们设定的特定标识,就能清楚的判断出到底是哪一部分代码出了错误,方便我们进行代码的排错。

代码分析

……
    try:
        netconfig_set_logserver(device_ip, nc_username, nc_password, log_name="log_center", log_server=log_server) 
        datacom_loop(device_ip, username, password, device_name)
        
    except KeyboardInterrupt:
        print("Monitoring has stopped!")
  1. 先看第6行,KeyboardInterrupt的意思是键盘中断,意思是在代码运行过程当中遇到了用户不小心按下ctrl+c的这种情况,要提示用户“Monitoring has stopped!” 监控已经停止
  2. 第2行的代码也很简单,就是两个函数或类带了一些参数
  3. 整体代码的含义大概是当用户运行了 netconfig_set_logserver和 datacom_loop这两个函数遇到时,如果遇到用户不小心按下ctrl+c的这种情况,要提示用户“Monitoring has stopped!” 监控已经停止
posted @ 2023-07-08 23:28  张贺贺呀  阅读(56)  评论(0编辑  收藏  举报