生活随笔
收集整理的這篇文章主要介紹了
Python try/except/finally等
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python try/except/finally等
[代碼塊] x?=?'abc'??def?fetcher(obj,?index):??????return?obj[index]????fetcher(x,?4)??輸出:
??File?"test.py",?line?6,?in?<module>??????fetcher(x,?4)????File?"test.py",?line?4,?in?fetcher??????return?obj[index]??IndexError:?string?index?out?of?range??
第一:?try不僅捕獲異常,而且會恢復執行
def?catcher():??????try:??????????fetcher(x,?4)??????except:??????????print?"got?exception"??????print?"continuing"?? 輸出:
got?exception??continuing??
第二:無論try是否發生異常,finally總會執行
def?catcher():??????try:??????????fetcher(x,?4)??????finally:??????????print?'after?fecth'?? 輸出:
after?fecth??Traceback?(most?recent?call?last):????File?"test.py",?line?55,?in?<module>??????catcher()????File?"test.py",?line?12,?in?catcher??????fetcher(x,?4)????File?"test.py",?line?4,?in?fetcher??????return?obj[index]??IndexError:?string?index?out?of?range??
第三:try無異常,才會執行else
def?catcher():??????try:??????????fetcher(x,?4)??????except:??????????print?"got?exception"??????else:??????????print?"not?exception"?? 輸出:
got?exception?? def?catcher():??????try:??????????fetcher(x,?2)??????except:??????????print?"got?exception"??????else:??????????print?"not?exception"?? 輸出:
not?exception?? else作用:沒有else語句,當執行完try語句后,無法知道是沒有發生異常,還是發生了異常并被處理過了。通過else可以清楚的區分開。
?
第四:利用raise傳遞異常
def?catcher():??????try:??????????fetcher(x,?4)??????except:??????????print?"got?exception"??????????raise?? 輸出:
got?exception??Traceback?(most?recent?call?last):????File?"test.py",?line?37,?in?<module>??????catcher()????File?"test.py",?line?22,?in?catcher??????fetcher(x,?4)????File?"test.py",?line?4,?in?fetcher??????return?obj[index]??IndexError:?string?index?out?of?range?? raise語句不包括異常名稱或額外資料時,會重新引發當前異常。如果希望捕獲處理一個異常,而又不希望
異常在程序代碼中消失,可以通過raise重新引發該異常。
?
第五:except(name1, name2)
def?catcher():??????try:??????????fetcher(x,?4)??????except(TypeError,?IndexError):??????????print?"got?exception"??????else:??????????print?"not?exception"?? 捕獲列表列出的異常,進行處理。若except后無任何參數,則捕獲所有異常。
def?catcher():??????try:??????????fetcher(x,?4)??????except: ?
轉載于:https://www.cnblogs.com/jp927/p/4535416.html
總結
以上是生活随笔為你收集整理的Python try/except/finally等的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。