Python try except異常捕獲機制原理解析
阿新 • • 發佈:2020-04-20
當你執行大型程式的時候,突然出現exception,會讓程式直接停止,這種對伺服器自動程式很不友好,而python有著較好的異常捕獲機制,不會立刻終止程式。
這個機制就是try-except。
1. 發生異常時可配置備用程式
aa = [1,2,4,5,7,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,1,'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,'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!!--- ')
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。