参考文献
https://www.jianshu.com/p/a8cb5375171a
https://www.jianshu.com/p/01ed4b8d7d9a
1 sys.exc_info()
import sys
try:
b = 2 + "b"
except Exception:
exc_type, exc_value, tracback_obj = sys.exc_info()
print(exc_type, "\n") # a为错误的类型
print("*" * 100)
print(exc_value, "\n") # b为错误的值
print("*" * 100)
print(tracback_obj, "\n") # c为tracback object对象
2 tracbace模块
该模块提供函数格式化处理sys.exc_info()返回的tracback object
2.1 print_tb()
该函数接受一下参数
tb: 这个就是traceback object, 是我们通过sys.exc_info获取到的
limit: 这个是限制stack trace层级的,如果不设或者为None,就会打印所有层级的stack trace
file: 这个是设置打印的输出流的,可以为文件,也可以是stdout之类的file-like object。如果不设或为None,则输出到sys.stderr。
import sys
import traceback
try:
b = 2 + "b"
except Exception:
exc_type, exc_value, tracback_obj = sys.exc_info()
traceback.print_tb(tracback_obj)
"""
返回以下值:
File "D:/ant_python_code/test_code.py", line 5, in <module>
b = 2 + "b"
"""
2.2 print_exception
该函数接受以下参数
跟print_tb相比多了两个参数etype和value,分别是exception type和exception value,加上tb(traceback object),正好是sys.exc_info()返回的三个值
另外,与print_tb相比,打印信息多了开头的"Traceback (most…)“信息以及最后一行的异常类型和value信息
还有一个不同是当异常为SyntaxError时,会有”^"来指示语法错误的位置
import sys
import traceback
try:
b = 2 + "b"
except Exception:
exc_type, exc_value, tracback_obj = sys.exc_info()
traceback.print_exception(exc_type, exc_value, tracback_obj)
# traceback.print_exception(*sys.exc_info)
"""
返回以下值:
Traceback (most recent call last):
File "D:/ant_python_code/test_code.py", line 5, in <module>
b = 2 + "b"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
2.3 print_exc
print_exc是简化版的print_exception, 由于exception type, value和traceback object都可以通过sys.exc_info()获取,因此print_exc()就自动执行exc_info()来帮助获取这三个参数了,也因此这个函数是我们的程序中最常用的,因为它足够简单
import traceback
try:
b = 2 + "b"
except Exception:
traceback.print_exc()
"""
返回以下值:
Traceback (most recent call last):
File "D:/ant_python_code/test_code.py", line 5, in <module>
b = 2 + "b"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
2.4 format_exc
我们想通过logger将异常记录在log里,这个时候就需要format_exc了,这个也是最常用的一个函数,它跟print_exc用法相同,只是不直接打印而是返回了字符串。
import traceback
try:
b = 2 + "b"
except Exception:
print(traceback.format_exc())
"""
返回以下值:
Traceback (most recent call last):
File "D:/ant_python_code/test_code.py", line 5, in <module>
b = 2 + "b"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""