python異常處理
異常處理的能力是一門語言好壞的重要特徵。python也提供了強大的異常處理功能,如下面介紹。
1. try...except :
[python]view plain
copy
try:
#raise nameerror
pass
except
nameerror:
# code to be executed when nameerror occurred
pass
except
valueerror:
# code to be executed when nameerror occurred
pass
上述**的執行規則如下:
首先,執行try語句中的語句。
如果在執行的過程中出現異常,則立即停止try語句的執行,執行異常處理或者停止執行(異常沒有處理)
發生異常後,將異常型別按順序與except語句中的異常匹配,如果匹配成功,執行對應的異常處理。如果匹配不成功。將異常傳遞給更高一級的try語句,如果異常一直未找到處理程式則停止執行,丟擲異常資訊。
執行流程圖如下:
有幾點需要注意:
例如:[python]view plain
copy
try:
raise
exception(
'spam'
, 'eggs'
) except
exception as inst :
(type(inst))
(inst.args)
#(argument tuple)
(inst) #
這段**中,丟擲異常時我們傳遞了兩個引數 spam和eggs,這兩個引數被組成乙個元組,儲存在異常例項的args屬性中,因此print inst.args將輸出(『spam』, 'eggs').由於這個異常例項定義了__str__方法,所以可以直接將它輸出,輸出結果與print inst.args一樣。如果乙個傳遞了引數的異常沒有被處理,那麼在丟擲的異常資訊最後一部分會是所傳遞的引數。假設上面丟擲的異常沒有處理(即去掉except語句),則輸出的異常資訊最後一部分是: exception: ('spam', 'eggs')
2. try ... except ... else:
else語句是可選的,它在沒有出現異常的時候被執行。也就是說,try語句沒有異常時,執行else語句。try語句出現異常時,按照1中的規則執行,忽略else語句。
3. try...finally
[python]view plain
copy
try:
#you do your operations here;
pass
#due to any exception, this may be skipped.
finally
: pass
#this would always be executed.
在這種情形中,finally語句總會被執行,無論try是否出現異常。
下面是乙個很好的例子:
[python]view plain
copy
try:
fh = open("testfile"
, "w"
) try
:
fh.write("this is my test file for exception handling!!"
) finally
: fh.close()
except
ioerror:
("error: can\'t find file or read data"
) else
("everything goes well"
)
上述**中,在執行內部try語句時,寫完檔案之後,finally一定會被執行,也就是檔案一定會關閉。這段**中有兩處可能出現異常,open和write。如果在open出現異常,內部try不被執行,直接進行異常處理輸出「error: can\'t find file or read data」。如果open不出現異常,繼續執行內部try,無論內部try是否出現異常close總會被執行。內部try出現異常,由於內部try沒有except語句,所以異常被傳遞給外部try語句,匹配ioerror成功,執行異常處理,輸出「error: can\'t find file or read data」。不出現異常的時候,執行else語句。
另乙個例子:
[python]view plain
copy
defdivide(x, y):
try:
result = x / y
except
zerodivisionerror:
("division by zero!"
) else
("result is"
, result)
finally
("executing finally clause"
)
執行divide(2, '2')時,結果如下:
executing finally clause
traceback (most recent call last):
file "d:\eclipse\workspace\python\exception\try_exception.py", line 11, in
divide(2,'2')
file "d:\eclipse\workspace\python\exception\try_exception.py", line 3, in divide
result = x / y
typeerror: unsupported operand type(s) for /: 'int' and 'str'
4. raise 丟擲異常
除了程式執行時出現異常外,我們也可以人為地丟擲任意型別的異常。e.g:
raise nameerror("test")
raise後面只能跟著乙個異常。這個異常可是是異常類,也可是是異常例項。
如果你只想知道是否出現異常,不想去處理異常,有一種方法可以重新丟擲異常:
[python]view plain
copy
try:
raise
nameerror(
"hello"
) except
nameerror:
"a nameeerror occurs"
raise
這段**執行結果如下:
a nameeerror occurs
traceback (most recent call last):
file "", line 2, in
raise nameerror("hello")
nameerror: hello
5. 自定義異常
python允許程式設計師通過繼承內建的異常型別來定製自己的異常型別。
[python]view plain
copy
class
myerror(exception):
def__init__(
self
, value):
self
.value = value
def__str__(
self
):
return
repr(
self
.value)
try:
raise
myerror(
4)
except
myerror as inst:
("opps, myerror occurred, value:"
, inst.value)
這段**執行結果為:opps, myerror occurred, value: 4
自定義異常型別的時候,盡量保持簡單,提供有效的異常資訊即可。
以上幾點只是簡單介紹,詳細內容請參考官方文件。
python異常處理 Python 異常處理
使用者輸入不完整 比如輸入為空 或者輸入非法 輸入不是數字 異常就是程式執行時發生錯誤的訊號,在python中,錯誤觸發的異常如下 在python中不同的異常可以用不同的型別 python中統一了類與型別,型別即類 去標識,不同的類物件標識不同的異常,乙個異常標識一種錯 觸發indexerror 觸...
python異常舉例 Python異常處理
1.1異常問題舉例 例一 i input 請輸入數字 請輸入數字 0 print i print 5 int i traceback most recent call last file line 1,in zerodivisionerror division by zero 上述 的報錯是除零的錯...
python異常處理
當你的程式中出現異常情況時就需要異常處理。比如當你開啟乙個不存在的檔案時。當你的程式中有一些無效的語句時,python會提示你有錯誤存在。下面是乙個拼寫錯誤的例子,print寫成了print。python是大小寫敏感的,因此python將引發乙個錯誤 print hello world file l...