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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM