Python Error inheritance table:
Https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Format:
def function ():
Try
Content # # #正确输出
Except error table in E:
Output Content # # #错误输出
Finally
Output Content # #必定输出
Print (' END ') # #必定输出
#!/usr/bin/python#-*-coding:utf-8-*-def foo (s): Return 10/int (s) def Bar (s): return foo (s) * 2def main (): TR Y:bar (' 0 ') except Exception as E:print (' Error: ', e) finally:print (' finally ... ') Main ( )
Operation Result:
(' Error: ', zerodivisionerror (' integer division or modulo by Zero ',)) finally ...
A. In the face of function layer calls, try...except can be captured.
B. Subclasses of the class can also be captured, such as capturing valueerror errors, and by the way the Unicodeerror are captured.
+--ValueError | +--Unicodeerror | +--Unicodedecodeerror | +--Unicodeencodeerror | +--Unicodetranslateerror
Logging errors to the log file:
#!/usr/bin/python#-*-coding:utf-8-*-import logging ########## #记得导入模块def foo (s): Return 10/int (s) def Bar (s): RE Turn foo (s) * 2def main (): Try:bar (' 0 ') except Exception as E:logging.exception (e) ######## #模块函数使用 Print (' haha ') main () print (' END ')
Operation Result:
hahaenderror:root:division by zerotraceback (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
When debugging without error, normal program error will call stack Traceback prompt error
def foo (s): Return 10/int (s) def Bar (s): return foo (s) * 2def main (): Bar (' 0 ') main ()
Operation Result:
Traceback (most recent): File "/usercode/file.py", line, <module> Main () file "/usercode/file.p Y ", line one, in main bar (' 0 ') of 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
Throw error: Raise
def foo (s): n = Int (s) if n==0:raise valueerror (' Invalid value:%s '% s) return 10/ndef bar (): Try: Foo (' 0 ') except ValueError as E:print (' valueerror! ', e) Raisebar ()
Operation Result:
(' valueerror! ', ValueError (' Invalid value:0 ',)) Traceback (most recent call last): File "/usercode/file.py", line +, in <module> bar () file "/usercode/file.py ", line A, in Bar foo (' 0 ') File"/usercode/file.py ", line 7, foo raise ValueError (' Invalid value:%s '% s) value Error:invalid value:0
Python error handling: try. Except. Finally/logging/raise