python try/except/finally__python

來源:互聯網
上載者:User

稍微總結一下,否則總是忘。

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"


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.