稍微總結一下,否則總是忘。
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 exceptioncontinuing
第二:無論try是否發生異常,finally總會執行
def catcher(): try: fetcher(x, 4) finally: print 'after fecth'
輸出:
after fecthTraceback (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 exceptionTraceback (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: print "got exception"