📜  如何在Python中打印异常堆栈跟踪?

📅  最后修改于: 2022-05-13 01:55:45.494000             🧑  作者: Mango

如何在Python中打印异常堆栈跟踪?

先决条件: Python Traceback

为了打印异常的堆栈跟踪,可疑代码将保留在 try 块中,并且将使用 except 块来处理生成的异常。在这里,我们将打印堆栈跟踪以处理生成的异常。打印异常堆栈跟踪有助于理解错误以及代码出了什么问题。不仅如此,堆栈跟踪还显示了错误发生的位置。

异常堆栈跟踪的一般结构:

例子:

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打印到文件。

代码:

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打印到文件。

代码

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