2024-09-27 00:11:13 发布
网友
在Python 2.7中,是否可以执行以下操作:
try: -command A- -command B- -command C- except ...: print("The exception occured during command " + failedCmd)
换句话说,有没有办法知道哪条语句在多行try块中失败,而不是将其分为3个不同的单行try块
谢谢
try: failedCmd = 'A' 1/10 # -command A- failedCmd = 'B' 1/0 # -command B- failedCmd = 'C' 1*0 # -command C- failedCmd = '' except: print("The exception occured during command " + failedCmd)
输出
The exception occured during command B
有一种使用traceback模块提取回溯信息的方法:
traceback
import traceback import sys try: def func(): raise TypeError: func() except TypeError: e = sys.exc_info()[2] print(traceback.extract_tb(e)[0][3])
哪张照片
func()
请看一下traceback.extract_tb(e)的完整输出,因为它为调用堆栈中的每个级别提供了元组列表。每一个都包含(file, line_no, module_or_func, line_text),您可能需要更改使用的值。在本例中,我使用了堆栈底部的行_文本(首先调用)
traceback.extract_tb(e)
(file, line_no, module_or_func, line_text)
使用sys获取引发异常的行号:
sys
import sys try: a = 1/2 b = 2/0 c = 3/-1 except Exception as e: trace_back = sys.exc_info()[2] print("Exception in line {}".format(trace_back.tb_lineno), e) # Exception in line 5 division by zero
输出
有一种使用
traceback
模块提取回溯信息的方法:哪张照片
请看一下
traceback.extract_tb(e)
的完整输出,因为它为调用堆栈中的每个级别提供了元组列表。每一个都包含(file, line_no, module_or_func, line_text)
,您可能需要更改使用的值。在本例中,我使用了堆栈底部的行_文本(首先调用)使用
sys
获取引发异常的行号:相关问题 更多 >
编程相关推荐