如何在Python中打印异常堆栈跟踪?
先决条件: Python Traceback
为了打印异常的堆栈跟踪,可疑代码将保留在 try 块中,并且将使用 except 块来处理生成的异常。在这里,我们将打印堆栈跟踪以处理生成的异常。打印异常堆栈跟踪有助于理解错误以及代码出了什么问题。不仅如此,堆栈跟踪还显示了错误发生的位置。
异常堆栈跟踪的一般结构:
- Traceback for the most recent call.
- Location of the program.
- Line in the program where the error was encountered.
- Name of the error: relevant information about the exception.
例子:
Traceback (most recent call last):
File "C:/Python27/hdg.py", line 5, in
value=A[5]
IndexError: list index out of range
方法一:使用print_exc()方法。
此方法将异常信息和堆栈跟踪条目从 traceback 对象tb打印到文件。
Syntax: traceback.print_exc(limit=None, file=None, chain=True)
Parameters: This method accepts the following parameters:
- if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed.
- If the file argument is None, the output goes to sys.stderr; otherwise, it should be an open file or file-like object to receive the output.
- If chain argument is true (the default), then chained exceptions will be printed as well, like the interpreter itself does when printing an unhandled exception.
Return: None.
代码:
Python3
# import module
import traceback
# declaring and assigning array
A = [1, 2, 3, 4]
# exception handling
try:
value = A[5]
except:
# printing stack trace
traceback.print_exc()
# out of try-except
# this statement is to show
# that program continues normally
# after an exception is handled
print("end of program")
Python3
# import required libraries
import traceback
import sys
# initialising variables
a = 4
b = 0
# exception handling
try:
value = a / b
except:
# printing stack trace
traceback.print_exception(*sys.exc_info())
# out of try-except
# this statement is to show
# that program continues
# normally after an exception is handled
print("end of program")
输出:
Traceback (most recent call last):
File "C:/Python27/hdg.py", line 8, in
value=A[5]
IndexError: list index out of range
end of program
方法二:使用print_exception()方法。
此方法将异常信息和堆栈跟踪条目从 traceback 对象tb打印到文件。
Syntax : traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
Parameters: This method accepts the following parameters:
- if tb argument is not None, it prints a header Traceback (most recent call last):
- it prints the exception etype and value after the stack trace
- if type(value) argument is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error.
- if a limit argument is positive, Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame). Otherwise, print the last abs(limit) entries. If the limit argument is None, all entries are printed.
- If the file argument is None, the output goes to sys.stderr; otherwise, it should be an open file or file-like object to receive the output.
- If chain argument is true (the default), then chained exceptions will be printed as well, like the interpreter itself does when printing an unhandled exception.
Return: None.
代码:
Python3
# import required libraries
import traceback
import sys
# initialising variables
a = 4
b = 0
# exception handling
try:
value = a / b
except:
# printing stack trace
traceback.print_exception(*sys.exc_info())
# out of try-except
# this statement is to show
# that program continues
# normally after an exception is handled
print("end of program")
输出:
Traceback (most recent call last):
File "C:/Python27/hdg.py", line 10, in
value=a/b
ZeroDivisionError: integer division or modulo by zero
end of program