Python sys.exc_info() 方法



Python sys.exc_info() 方法,该方法返回一个元组,其中包含有关 except 子句捕获的最新异常的信息。元组由三个元素组成,它们是异常类型、异常值和回溯对象。

此方法对于错误处理和调试特别有用,因为它提供有关异常上下文的详细信息。通过使用 'sys.exc_info()' 方法,开发人员可以通过改进其应用程序中的错误记录和处理功能,以编程方式访问和操作异常详细信息。

语法

以下是 Python sys.exc_info() 方法的语法和参数 -


 sys.exc_info()

参数

此方法不返回任何值。

返回值

此方法返回包含三个值 (type、value、traceback) 的 Tuples。

示例 1

下面是引发并捕获 ZeroDivisionError 的基本示例。sys.exc_info() 方法检索有关异常的信息 -


import sys

try:
	 	 1 / 0
except ZeroDivisionError:
	 	 exc_type, exc_value, exc_traceback = sys.exc_info()
	 	 print(f"Exception type: {exc_type}")
	 	 print(f"Exception value: {exc_value}")
	 	 print(f"Traceback object: {exc_traceback}")

输出

Exception type: <class 'ZeroDivisionError'>
Exception value: division by zero
Traceback object: <traceback object at 0x0000016DCBD35000>

示例 2

此示例使用 sys.exc_info() 方法检索异常详细信息,然后使用 traceback 模块打印 traceback 详细信息 -


import sys
import traceback

def divide(a, b):
	 	 try:
	 	 	 	 return a / b
	 	 except ZeroDivisionError:
	 	 	 	 exc_type, exc_value, exc_traceback = sys.exc_info()
	 	 	 	 print(f"Exception type: {exc_type}")
	 	 	 	 print(f"Exception value: {exc_value}")
	 	 	 	 print("Traceback details:")
	 	 	 	 traceback.print_tb(exc_traceback)

divide(1, 0)

输出

Exception type: <class 'ZeroDivisionError'>
Exception value: division by zero
Traceback details:
File "\sample.py", line 6, in divide
return a / b
~~^~~

示例 3

现在,在这个例子中,我们展示了如何在自定义函数中构建嵌套异常处理 -


import sys
import traceback

try:
	 	 try:
	 	 	 	 result = int('not a number')
	 	 except ValueError:
	 	 	 	 exc_type, exc_value, exc_traceback = sys.exc_info()
	 	 	 	 print("Inner exception info:")
	 	 	 	 print(f" 	Type: {exc_type}")
	 	 	 	 print(f" 	Value: {exc_value}")
	 	 	 	 traceback.print_tb(exc_traceback)
	 	 	 	 # Re-raise the exception to the outer try block
	 	 	 	 raise
except Exception as e:
	 	 print("Outer exception info:")
	 	 exc_type, exc_value, exc_traceback = sys.exc_info()
	 	 print(f" 	Type: {exc_type}")
	 	 print(f" 	Value: {exc_value}")
	 	 traceback.print_tb(exc_traceback)

输出

Inner exception info:
Type: <class 'ValueError'>
Value: invalid literal for int() with base 10: 'not a number'
File "\sample.py", line 6, in <module>
result = int('not a number')
^^^^^^^^^^^^^^^^^^^
Outer exception info:
Type: <class 'ValueError'>
Value: invalid literal for int() with base 10: 'not a number'
File "\sample.py", line 6, in <module>
result = int('not a number')
^^^^^^^^^^^^^^^^^^^