python使用異常物件來表示異常狀態,並在遇到錯誤時引發異常,異常物件未被處理時,程式將終止並顯示一條錯誤資訊。
raise語句
自定義異常類
class
somecustomexception
(exception)
:pass
class
myexceptionclass
(exception)
:def
__init__
(self, code, msg)
: self.code = code
self.msg = msg
super
(myexceptionclass, self)
.__init__(
) @staticmethod
deftest()
: content =
input
("input str:")if
len(content)
>5:
raise myexceptionclass(
'1001'
,'長度小於5'
# raise myexceptionclass('1001', '長度小於5')
# __main__.myexceptionclass
class
trydemo
(object):
deftest
(self)
: a =
int(
input
("輸入第乙個數:"))
('\n'
) b =
int(
input
("輸入第二個數:"))
(a / b)
if __name__ ==
'__main__'
: trydemo = trydemo(
) trydemo.test(
)
捕獲異常輸入第乙個數:10
輸入第二個數:0
不用提供引數def
test()
: a =
int(
input
("輸入第乙個數:"))
b =int(
input
("輸入第二個數:"))
try:
(a / b)
except zerodivisionerror:
("第二個數不能為0"
)class
trydemo
(object):
pass
if __name__ ==
'__main__'
: trydemo = trydemo(
) test(
)輸入第乙個數:10
輸入第二個數:0
第二個數不能為0
python 中的異常處理
python的異常處理能力是很強大的,可向使用者準確反饋出錯資訊。在python中,異常也是物件,可對它進行操作。所有異常都是基類exception的成員。所有異常都從基類exception繼承,而且都在exceptions模組中定義。python自動將所有異常名稱放在內建命名空間中,所以程式不必匯...
Python中的異常處理
當python檢測到乙個錯誤時,直譯器就無法繼續執行了,反而出現了一些錯誤的提示,這就是所謂的 異常 看如下示例 try print test1 open 123.txt r print test2 except ioerror pass此時可以正常執行,執行結果為 test1 說明 try exc...
Python中的異常處理
目錄 異常處理 python中常見的異常 在python當中,若乙個程式在執行的時候出錯,python直譯器會自動的在出錯的地方生成乙個異常物件,而後python直譯器會自動的在出錯地方的附近尋找有沒有對這個異常物件處理的 所謂異常處理 就是 try except 語句。如果沒有,python直譯器...