在用户定义的异常处理之后正确的一般异常处理

时间:2021-06-12 13:50:19

标签: python exception error-handling logic

从逻辑上讲,我想将用户定义的异常与一般异常处理联系起来。首先应该检查是否触发了用户定义的异常。如果没有触发,但是又出现了异常,我想通过get_exception_info()打印异常信息。

我有以下代码:

class TestException(Exception):
    pass

def get_exception_info():
    try:
        exception_type, exception_value, exception_traceback = sys.exc_info()
        file_name, line_number, procedure_name, line_code = traceback.extract_tb(exception_traceback)[-1] #this line is properly indented in my file
        exception_info = ''.join('[Time Stamp]: '
            + str(time.strftime('%d-%m-%Y %I:%M:%S %p'))
            + '' + '[File Name]: ' + str(file_name) + ' '
            + '[Procedure Name]: ' + str(procedure_name) + ' '
            + '[Error Message]: ' + str(exception_value) + ' '
            + '[Error Type]: ' + str(exception_type) + ' '
            + '[Line Number]: ' + str(line_number) + ' '
            + '[Line Code]: ' + str(line_code))
        return exception_info
    except:
        pass

def test_func(x):

    try:
        if x > 0:
            raise TestException('wrong')
        elif x < 0:
            raise TestException('right')
        else:
            pass
    except TestException as e:
        print(e)
    except Exception:
        exception_info = get_exception_info()
        print(exception_info)
    finally:
        pass

test_func(a) 

理论上,这会导致异常,它应该打印出 get_exception_info() 的结果。但是我只是得到“NameError:名称'a'未定义。

我做错了什么?而且,更重要的是,这是实现我的目标的正确方法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

该错误表明您传递给 a 的值 test_func() 未定义。

添加一行定义 a,例如:

# ...
a = "hello"
test_func(a)

编辑:

为了让您的代码正常工作,您还需要导入 timetracebacksys。我还建议不要在 get_exception_info() 内捕获异常,因为这可能会隐藏您真正想看到的异常,即:

import time
import traceback
import sys

class TestException(Exception):
    pass

def get_exception_info():
    exception_type, exception_value, exception_traceback = sys.exc_info()
    file_name, line_number, procedure_name, line_code = traceback.extract_tb(exception_traceback)[-1]
    exception_info = ' '.join([
        '[Time Stamp]:',
        time.strftime('%d-%m-%Y %I:%M:%S %p'),
        '[File Name]:',
        file_name,
        '[Procedure Name]:',
        procedure_name,
        '[Error Message]:',
        str(exception_value),
        '[Error Type]:',
        str(exception_type),
        '[Line Number]:',
        str(line_number),
        '[Line Code]:',
        line_code,
    ])

    return exception_info
# ...

编辑二:

听起来这个问题围绕着如何捕获未定义的变量(在本例中为 a)。

在这种情况下,我建议在函数调用周围添加一个 try-except 块,例如:

try:
    test_func(a)
except Exception:
    exception_info = get_exception_info()
    print(exception_info)

a 未定义时,这将生成以下内容:

[Time Stamp]: 13-06-2021 10:44:31 AM [File Name]: /path/to/sf_exc.py [Procedure Name]: <module> [Error Message]: name 'a' is not defined [Error Type]: <class 'NameError'> [Line Number]: 76 [Line Code]: test_func(a)

评论

一般来说,我会使用 Python 的 logging 模块,而不是手动格式化错误消息,该模块功能强大,在格式化不同类型的消息时提供了很大的灵活性,使用自定义 {{ 3}}。特别是,Formatter 附带了可以自定义以处理 Formatterexceptions 的方法。

相关问题