Pythonでは、例外が発生した際にその原因を取得する方法があります。具体的には、例外オブジェクトの __cause__
属性を使用します。
例えば、次のようなコードがあります。
try:
raise CustomException()
except CustomException as e:
try:
raise TypeError() from e
except TypeError as e:
print(type(e.__cause__))
このコードでは、CustomException
が発生し、それを TypeError
として再度発生させています。そして、TypeError
の __cause__
属性を表示しています。結果として、<class '__main__.CustomException'>
が出力されます。
しかし、元の例外をキャッチする方法はありません。つまり、次のようなコードは機能しません。
try:
raise CustomException()
except CustomException as e:
try:
raise TypeError() from e
except CustomException as e:
print(type(e))
このコードでは、TypeError
が発生していますが、CustomException
をキャッチしようとしています。そのため、この except
ブロックは実行されません。
しかし、すべての例外をキャッチし、必要なものだけをフィルタリングするという方法があります。
try:
raise ZeroDivisionError()
except ZeroDivisionError as e:
try:
raise TypeError() from e
except Exception as ex:
if type(ex.__cause__) is ZeroDivisionError:
print('ZeroDivisionError')
else:
raise # re-raise exception if it has different __cause__
このコードでは、すべての例外をキャッチし、__cause__
が ZeroDivisionError
の場合だけ特定の処理を行います。
以上が、Pythonで例外の原因を取得する方法についての説明です。この情報がPythonの例外処理を理解するのに役立つことを願っています。