Python try/except/finally


舉例說明一下try/except/finally的用法。

 

若不使用try/except/finally

1 x = 'abc'
2 def fetcher(obj, index):
3     return obj[index]
4 
5 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/except/finally:

第一: try不僅捕獲異常,而且會恢復執行

1 def catcher():
2     try:
3         fetcher(x, 4)
4     except:
5         print "got exception"
6     print "continuing"

輸出:

got exception
continuing

 

第二:無論try是否發生異常,finally總會執行

1 def catcher():
2     try:
3         fetcher(x, 4)
4     finally:
5         print 'after fecth'

輸出:(這里沒用except,即沒有在異常發生時的處理辦法,就按python默認的方式來對待異常發生,故程序會停下來)

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

有異常的情況

1 def catcher():
2     try:
3         fetcher(x, 4)
4     except:
5         print "got exception"
6     else:
7         print "not exception"

輸出:

got exception  

 

沒異常的情況:

1 def catcher():
2     try:
3         fetcher(x, 2)
4     except:
5         print "got exception"
6     else:
7         print "not exception"

輸出:

not exception  

else作用:沒有else語句,當執行完try語句后,無法知道是沒有發生異常,還是發生了異常並被處理過了。通過else可以清楚的區分開。

 

第四:利用raise傳遞異常

1 def catcher():
2     try:
3         fetcher(x, 4)
4     except:
5         print "got exception"
6         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語句不包括異常名稱或額外資料時,會重新引發當前異常(即發生了異常才進入except內的異常)。如果希望捕獲處理一個異常,而又不希望異常在程序代碼中消失,可以通過raise重新引發該異常。

 

第五:except(name1, name2)

1 def catcher():
2     try:
3         fetcher(x, 4)
4     except(TypeError, IndexError):
5         print "got exception"
6     else:
7         print "not exception"

捕獲列表列出的異常,進行處理。若except后無任何參數,則捕獲所有異常。

1 def catcher():
2     try:
3         fetcher(x, 4)
4     except:
5         print "got exception"

 


免責聲明!

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



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