次のような抽象基本クラスを持つ例外クラスがあるとします。
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 の実装には怪しげなショートカットがいくつかあるでしょう。