假设我有一个带有抽象基类的异常类,如下所示:
class MyExceptions(BaseExeption, metaclass=abc.ABCMeta):
pass
class ProperSubclass(MyExceptions):
pass
MyExceptions.register(ValueError)
看来我可以赶上ProperSubclass
,MyExceptions
但不是ValueError
:
try:
raise ProperSubclass()
except MyExceptions:
print('As expected, control comes here...')
except:
print('...and not here.')
try:
raise ValueError()
except MyExceptions:
print('Control does not come here...')
except ValueError:
print('...but unexpectedly comes here.')
所以我的问题是,我应该能够通过它们的抽象基类捕获内置异常吗?如果是这样,怎么做?如果没有,规则是什么?
我想问这个问题的另一种方式是:除了子句是否正确使用 isinstance()/issubclass() 进行匹配,如果没有(似乎是这种情况)它们使用什么?也许在 C 实现中有一些阴暗的捷径。