Python 有没有一种方法可以处理异常,但只能从特定的库中处理?

Python 有没有一种方法可以处理异常,但只能从特定的库中处理?,python,python-2.7,exception-handling,Python,Python 2.7,Exception Handling,我正在使用一个包(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: excep

我正在使用一个包(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.basefootexception
类的子类,则可以捕获它:

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

库应该(希望)有礼貌地实现一个基本异常,其他异常从中派生出来?因此,它只是:exception BaseExceptionClass:?可能更简单的方法是将
所有异常
创建一个元组,并将
所有异常作为e