$ python3 err.py Traceback (most recent call last): File "err.py", line 11, in <module> main() File "err.py", line 9, in main bar('0') File "err.py", line 6, in bar return foo(s) * 2 File "err.py", line 3, in foo return10 / int(s) ZeroDivisionError: division by zero
由上往下,依次是错误的跟踪信息,由引发点,最终至错误产生的源头。
原因是:ZeroDivisionError: division by zero ,因此判断 10 / 0 出错。
记录错误
如果我们捕获错误,就可以把错误堆栈打印出来,然后分析错误原因,同时让程序继续执行下去。
Python 的内置 logging 模块可以非常容易地记录错误信息:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import logging
deffoo(s): return10 / int(s)
defbar(s): return foo(s) * 2
defmain(): try: bar('0') except Exception as e: logging.exception(e)
$ python3 err_logging.py ERROR:root:division by zero Traceback (most recent call last): File "err_logging.py", line 13, in main bar('0') File "err_logging.py", line 9, in bar return foo(s) * 2 File "err_logging.py", line 6, in foo return10 / int(s) ZeroDivisionError: division by zero END