gpt4 book ai didi

python - 有没有办法处理异常但只能处理来自特定库的异常?

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:10 24 4
gpt4 key购买 nike

我正在使用一个包 (foo) 并调用该包内的类 (Foo) 中的方法。假设该包定义了自己的异常:

exception foo.exceptions.FooEx_1
exception foo.exceptions.FooEx_2
...
exception foo.exceptions.FooEx_n

我不想编写通用异常处理程序:

try:
except:
# Process any exception here

我只想捕获 foo 库/包中引发的异常。有没有办法做到这一点?喜欢:

try:
except foo.exceptions.*

最佳答案

如果 foo.exceptions 中的所有异常都是某个基 foo.exceptions.BaseFooException 类的子类,则可以捕获它:

>>> assert issubclass(NotImplementedError, RuntimeError)
>>>
>>> try:
... raise NotImplementedError()
... except RuntimeError:
... print('Caught it')
...
Caught it

否则,您将必须从模块中提取所有异常:

all_exceptions = tuple(getattr(foo.exceptions, e) for e in dir(foo.exceptions) if e.startswith('FooEx'))

并对它们进行过滤:

try:
...
except all_exceptions as e:
# We caught it

关于python - 有没有办法处理异常但只能处理来自特定库的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com