目录
一、try except异常处理的语句格式
二、获取相关异常信息
(1)sys.exec_info()
三、traceback模块的常用方式
(1)traceback.print_tb(tb, limit=None, file=None) 打印指定堆栈异常信息
(2)traceback.print_exception(exc, /, [value, tb, ]limit=None, file=None, chain=True) 和 traceback.print_exc(limit=None, file=None, chain=True) 打印指定堆栈异常信息
(3)traceback.format_list(extracted_list) 和 traceback.format_exception(exc, /, [value, tb, ]limit=None, chain=True) 返回可打印的错误信息字符串列表
(4)和 traceback.format_exc(limit=None, chain=True) 返回错误信息字符串
一、try except异常处理的语句格式
try:
可能产生异常的代码块
except [ (Error1, Error2, ... ) [as e] ]:
处理异常的代码块1
except [ (Error3, Error4, ... ) [as e] ]:
处理异常的代码块2
except [Exception]:
处理其它异常
finally:
最后做其他事情,finally必定执行
二、获取相关异常信息
(1)sys.exec_info()
sys.exc_info() 该函数会返回一个元组(type(e), e, e.__traceback__)。
该元组记录错误类型、错误信息、错误信息所在堆栈。如果没有异常发生,则会返回一个空的元组
示例:
import sys
import traceback
def func(a: int, b: int):
return a // b
def func1(a: int, b: int):
try:
return func(a, b)
except Exception as e:
errType, errInfo, errTraceBack = sys.exc_info()
print(errType) # <class 'ZeroDivisionError'>
print(errInfo) # integer division or modulo by zero
print(errTraceBack) # <traceback object at 0x000001FEF8C7BB80>
if __name__ == "__main__":
func1(1, 0)
三、traceback模块的常用方式
相关官方文档:traceback —— 打印或读取堆栈的跟踪信息 — Python 3.11.2 文档
(1)traceback.print_tb(tb, limit=None, file=None) 打印指定堆栈异常信息
- traceback.print_tb(tb, limit=None, file=None) 其中tb指的是从sys.exc_info()获取的traceback堆栈类型,limit指的是报告错误的堆栈层数,file指的是输出到哪个文件流中,默认为stderr
import sys
import traceback
def func(a: int, b: int):
return a // b
def func1(a: int, b: int):
try:
return func(a, b)
except Exception as e:
errType, errInfo, errTraceBack = sys.exc_info()
traceback.print_tb(errTraceBack)
'''
File "d:\Python WorkSpace\GameAssist\test2.py", line 10, in func1
return func(a, b)
File "d:\Python WorkSpace\GameAssist\test2.py", line 6, in func
return a // b
'''
if __name__ == "__main__":
func1(1, 0)
(2)traceback.print_exception(exc, /, [value, tb, ]limit=None, file=None, chain=True) 和 traceback.print_exc(limit=None, file=None, chain=True) 打印指定堆栈异常信息
- traceback.print_exception(exc, /, [value, tb, ]limit=None, file=None, chain=True) 打印回溯对象 tb 到 file 的异常信息和整个堆栈回溯。
- traceback.print_exc(limit=None, file=None, chain=True) 相当于
print_exception(*sys.exc_info(), limit, file, chain)
的简写
import sys
import traceback
def func(a: int, b: int):
return a // b
def func1(a: int, b: int):
try:
return func(a, b)
except Exception as e:
traceback.print_exception(e)
traceback.print_exception(e, file=open("./ErrorLog.txt", "a+"))
'''
Traceback (most recent call last):
File "d:\Python WorkSpace\GameAssist\test2.py", line 9, in func1
return func(a, b)
File "d:\Python WorkSpace\GameAssist\test2.py", line 5, in func
return a // b
ZeroDivisionError: integer division or modulo by zero
'''
if __name__ == "__main__":
func1(1, 0)
(3)traceback.format_list(extracted_list) 和 traceback.format_exception(exc, /, [value, tb, ]limit=None, chain=True) 返回可打印的错误信息字符串列表
- traceback.format_list(extracted_list)给定一个由元组或如 extract_tb() 或 extract_stack() 所返回的 FrameSummary 对象组成的列表,返回一个可打印的字符串列表
import sys
import traceback
def func(a: int, b: int):
return a // b
def func1(a: int, b: int):
try:
return func(a, b)
except Exception as e:
errType, errInfo, errTraceBack = sys.exc_info()
print(traceback.format_list(traceback.extract_tb(errTraceBack)))
'''
[' File "d:\\Python WorkSpace\\GameAssist\\test2.py", line 9, in func1\n return func(a, b)\n', ' File "d:\\Python WorkSpace\\GameAssist\\test2.py", line 5, in func\n return a // b\n']
'''
if __name__ == "__main__":
func1(1, 0)
- traceback.format_exception(exc, /, [value, tb, ]limit=None, chain=True) 格式化一个栈跟踪和异常信息。 参数的含义与传给 print_exception() 的相应参数相同。 返回值是一个字符串列表,每个字符串都以一个换行符结束且有些还包含内部换行符。
import sys
import traceback
def func(a: int, b: int):
return a // b
def func1(a: int, b: int):
try:
return func(a, b)
except Exception as e:
print(traceback.format_exception(e))
'''
['Traceback (most recent call last):\n', ' File "d:\\Python WorkSpace\\GameAssist\\test2.py", line 9, in func1\n return func(a, b)\n', ' File "d:\\Python WorkSpace\\GameAssist\\test2.py", line 5, in func\n return a // b\n', 'ZeroDivisionError: integer division or modulo by zero\n']
'''
if __name__ == "__main__":
func1(1, 0)
(4)和 traceback.format_exc(limit=None, chain=True) 返回错误信息字符串
- traceback.format_exc(limit=None, chain=True) 这类似于
print_exc(limit)
但会返回一个字符串而不是打印到一个文件
import sys
import traceback
def func(a: int, b: int):
return a // b
def func1(a: int, b: int):
try:
return func(a, b)
except Exception as e:
print(traceback.format_exc())
'''
Traceback (most recent call last):
File "d:\Python WorkSpace\GameAssist\test2.py", line 9, in func1
return func(a, b)
File "d:\Python WorkSpace\GameAssist\test2.py", line 5, in func
return a // b
ZeroDivisionError: integer division or modulo by zero
'''
if __name__ == "__main__":
func1(1, 0)