有没有办法访问python3回溯中发生的“另一个异常”?

lb3vh1jj  于 2023-02-14  发布在  Python
关注(0)|答案(1)|浏览(121)

让我们假设您有一些简单的代码,* 您无法控制 *(例如:它位于您正在使用的模块中):

def example():
    try:
        raise TypeError("type")
    except TypeError:
        raise Exception("device busy")

为了处理它,我将如何着手访问这个回溯中的TypeError

Traceback (most recent call last):
  File "/usr/local/google/home/dthor/dev/pyle/pyle/fab/visa_instrument/exception_helpers.py", line 3, in example
    raise TypeError("type")
TypeError: type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/google/home/dthor/dev/pyle/pyle/fab/visa_instrument/exception_helpers.py", line 7, in <module>
    example()
  File "/usr/local/google/home/dthor/dev/pyle/pyle/fab/visa_instrument/exception_helpers.py", line 5, in example
    raise Exception("device busy")
Exception: device busy

我可以做下面的操作,但我不满意,因为我正在做字符串比较--这意味着如果底层模块改变了它们所引发的字符串,事情就会中断(我不控制example()):

try:
    example()
except Exception as err:
    if "device busy" in str(err):
        # do the thing
        pass
    # But raise any other exceptions
    raise err

我更希望:

try:
    example()
except Exception as err:
    if TypeError in err.other_errors:  # magic that doesn't exist
        # do the thing
        pass
    raise err

甚至

try:
    example()
except TypeError in exception_stack:  # Magic that doesn't exist
    # do the thing
    pass
except Exception:

我正在研究traceback模块和sys.exc_info(),但还没有任何具体的东西。
跟进:如果异常是 chained,情况会有所不同吗?raise Exception from the_TypeError_exception

yizd12fk

yizd12fk1#

检查异常的__context__

>>> try:
...     example()
... except Exception as e:
...     print(f"exception: {e!r}")
...     print(f"context: {e.__context__!r}")
...
exception: Exception('device busy')
context: TypeError('type')

如果使用链式异常,则原始异常也可以通过__cause__属性访问。

相关问题