Python try except異常捕獲機(jī)制原理解析
當(dāng)你執(zhí)行大型程序的時候,突然出現(xiàn)exception,會讓程序直接停止,這種對服務(wù)器自動程序很不友好,而python有著較好的異常捕獲機(jī)制,不會立刻終止程序。
這個機(jī)制就是try-except。
1. 發(fā)生異常時可配置備用程序
aa = [1,2,4,5,7,0,2]for ii in aa: try: h = 2/ii print(h) except: #發(fā)生異常時備用 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. 多個異常捕獲,循環(huán)中
num = [9,7,0,1,4,’16’]for x in num: try: print (1/x) except ZeroDivisionError: print(’error:0做除數(shù)!’) except TypeError: # 當(dāng)報錯信息為TypeError,執(zhí)行下面的語句。 print(’error:數(shù)值類型錯誤!’)print(’ ---finished!!--- ’)
4. 通用異常:Exception,當(dāng)你不知道異常的種類或者多少異常的時候,可以使用通用異常捕獲,同時通用異常可以與特定異常混用。
num = [9,7,0,1,4,’16’]for x in num: try: print (1/x) except ZeroDivisionError: print(’error:0做除數(shù)!’) #特定異常和Exception混合使用 except Exception as e: print(’the Exception is:’,e)print(’ ---finished!!--- ’)
5. else語句:在被檢測的代碼塊沒有發(fā)生異常時執(zhí)行
dict_ = {’test’:’這個地方是哪里?’}try: print(dict_[’test’]) print(’ --- testing... --- ’)except KeyError as e: print(’--- the error is ---:’, e) #單個異常else: print(’沒有發(fā)生異常!’)print(’ ---finished!!--- ’)
6. finally語句:不管有沒有發(fā)生異常都會執(zhí)行
dict_ = {’test’:’這個地方是哪里?’}try: print(dict_[’test’]) print(’ --- testing... --- ’)except KeyError as e: print(’--- the error is ---:’, e) #單個異常else: print(’沒有發(fā)生異常!’)finally: print(’總可以被執(zhí)行的語句。。。’)print(’ ---finished!!--- ’)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決Python中報錯TypeError: must be str, not bytes問題2. Python如何解決secure_filename對中文不支持問題3. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考4. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識)5. 不使用XMLHttpRequest對象實(shí)現(xiàn)Ajax效果的方法小結(jié)6. Python類成員繼承重寫的實(shí)現(xiàn)7. 使用python tkinter開發(fā)一個爬取B站直播彈幕工具的實(shí)現(xiàn)代碼8. Python 用NumPy創(chuàng)建二維數(shù)組的案例9. ThinkPHP6使用JWT+中間件實(shí)現(xiàn)Token驗(yàn)證實(shí)例詳解10. python安裝sklearn模塊的方法詳解
