您好,登錄后才能下訂單哦!
python錯誤繼承表:
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
格式:
def 函數(shù)():
try:
內(nèi)容 ###正確輸出
except 錯誤表 in e:
輸出內(nèi)容 ###錯誤輸出
finally:
輸出內(nèi)容 ##必定輸出
print('END') ##必定輸出
#!/usr/bin/python # -*- coding: utf-8 -*- def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: print('Error:', e) finally: print('finally...') main()
運行結(jié)果:
('Error:', ZeroDivisionError('integer division or modulo by zero',)) finally...
a.面對函數(shù)層層調(diào)用,try...except能捕捉得到。
b.類的子類錯誤也能捕捉得到,如捕捉ValueError錯誤,順便也會把UnicodeError也捕捉了
+-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError
記錄錯誤到日志文件:
#!/usr/bin/python # -*- coding: utf-8 -*- import logging ###########記得導入模塊 def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) #########模塊函數(shù)使用 print ('haha') main() print ('END')
運行結(jié)果:
haha END ERROR:root:division by zero Traceback (most recent call last): File "/usercode/file.py", line 14, in main bar('0') File "/usercode/file.py", line 10, in bar return foo(s) * 2 File "/usercode/file.py", line 7, in foo return 10 / int(s) ZeroDivisionError: division by zero
當不用錯誤調(diào)試時,普通的程序出錯會調(diào)用棧Traceback提示錯誤
def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): bar('0') main()
運行結(jié)果:
Traceback (most recent call last): File "/usercode/file.py", line 13, in <module> main() File "/usercode/file.py", line 11, in main bar('0') File "/usercode/file.py", line 8, in bar return foo(s) * 2 File "/usercode/file.py", line 5, in foo return 10 / int(s) ZeroDivisionError: integer division or modulo by zero
拋出錯誤:raise
def foo(s): n = int(s) if n==0: raise ValueError('invalid value: %s' % s) return 10 / n def bar(): try: foo('0') except ValueError as e: print('ValueError!', e) raise bar()
運行結(jié)果:
('ValueError!', ValueError('invalid value: 0',)) Traceback (most recent call last): File "/usercode/file.py", line 17, in <module> bar() File "/usercode/file.py", line 12, in bar foo('0') File "/usercode/file.py", line 7, in foo raise ValueError('invalid value: %s' % s) ValueError: invalid value: 0
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。