确定在多行尝试中失败的语句

2024-09-27 00:11:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python 2.7中,是否可以执行以下操作:

try:
   -command A-
   -command B-
   -command C-
except ...:
   print("The exception occured during command " + failedCmd)

换句话说,有没有办法知道哪条语句在多行try块中失败,而不是将其分为3个不同的单行try块

谢谢


Tags: theexception语句commandprinttryexcept单行
3条回答
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模块提取回溯信息的方法:

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),您可能需要更改使用的值。在本例中,我使用了堆栈底部的行_文本(首先调用)

使用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

相关问题 更多 >

    热门问题