Python的try/except异常捕获机制

当你执行大型程序的时候,突然出现exception,会让程序直接停止,这种对服务器自动程序很不友好,而python有着较好的异常捕获机制,不会立刻终止程序。

这个机制就是try-except。

1. 发生异常时可配置备用程序

aa = [1,2,4,5,7,0,2]

for ii in aa:
    try:
        h = 2/ii
        print(h)
    except:   #发生异常时备用
        h = 2/(ii+1)
        print(h)

2. 单个异常捕获

dict_ = {}
try:
    print(dict_['test'])
    print(' --- testing... --- ')
except KeyError as e:
    print('--- the error is ---:', e)   #单个异常
print(' ---finished!!--- ') 

3. 多个异常捕获,循环中

num = [9,7,0,1,4,'16']
for x in num:
    try: 
        print (1/x)
    except ZeroDivisionError:
        print('error:0做除数!')
    except TypeError:  # 当报错信息为TypeError,执行下面的语句。
        print('error:数值类型错误!')
print(' ---finished!!--- ') 

4. 通用异常:Exception,当你不知道异常的种类或者多少异常的时候,可以使用通用异常捕获,同时通用异常可以与特定异常混用

num = [9,7,0,1,4,'16']
for x in num:
    try: 
        print (1/x)
    except ZeroDivisionError:
        print('error:0做除数!')   #特定异常和Exception混合使用
    except Exception as e:
        print('the Exception is:',e)
print(' ---finished!!--- ') 

5. else语句:在被检测的代码块没有发生异常时执行

dict_ = {'test':'这个地方是哪里?'}
try:
    print(dict_['test'])
    print(' --- testing... --- ')
except KeyError as e:
    print('--- the error is ---:', e)   #单个异常
else:
    print('没有发生异常!')
print(' ---finished!!--- ') 

6. finally语句:不管有没有发生异常都会执行

dict_ = {'test':'这个地方是哪里?'}
try:
    print(dict_['test'])
    print(' --- testing... --- ')
except KeyError as e:
    print('--- the error is ---:', e)   #单个异常
else:
    print('没有发生异常!')
finally:
    print('总可以被执行的语句。。。')
print(' ---finished!!--- ') 

##

参考:

https://www.cnblogs.com/Through-Target/p/12096410.html

https://www.cnblogs.com/xudachen/p/8672352.html

posted on 2020-04-15 22:10  落日峡谷  阅读(4708)  评论(0编辑  收藏  举报

导航