[python] view plaincopyprint?
x = 'abc'
def fetcher(obj, index):
return obj[index]
fetcher(x, 4)
輸出:
[plain] view plaincopyprint?
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不僅捕獲異常,而且會恢復執行
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 4)
except:
print "got exception"
print "continuing"
輸出:
[plain] view plaincopyprint?
got exception
continuing
第二:無論try是否發生異常,finally總會執行
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 4)
finally:
print 'after fecth'
輸出:
[plain] view plaincopyprint?
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
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 4)
except:
print "got exception"
else:
print "not exception"
輸出:
[plain] view plaincopyprint?
got exception
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 2)
except:
print "got exception"
else:
print "not exception"
輸出:
[plain] view plaincopyprint?
not exception
else作用:沒有else語句,當執行完try語句後,無法知道是沒有發生異常,還是發生了異常並被處理過了。通過else可以清楚的區分開。
第四:利用raise傳遞異常
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 4)
except:
print "got exception"
raise
輸出:
[plain] view plaincopyprint?
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)
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 4)
except(TypeError, IndexError):
print "got exception"
else:
print "not exception"
捕獲列表列出的異常,進行處理。若except後無任何參數,則捕獲所有異常。
[python] view plaincopyprint?
def catcher():
try:
fetcher(x, 4)
except:
print "got exception"
http://blog.csdn.net/spch2008/article/details/9343207