Open2
Python Exception Context
Exception を検知したらそのExceptionを引き継いでカスタム属性を付与した例外を新たに投げたいというケースがあったのでメモ
参考
検証用コード
import traceback
class MyException(Exception):
def __init__(self, message, cutom):
super().__init__(message)
self.custom = cutom
test = [0, 1, 2]
def do():
try:
print(test[3])
except Exception as err:
print(repr(err))
print("------------")
raise MyException(repr(err), "test") from err
def main():
try:
do()
except BaseException as err:
print(repr(err))
print("------------")
print(traceback.format_exc())
print("------------")
print(err.custom)
main()
出力:
IndexError('list index out of range')
------------
MyException("IndexError('list index out of range')")
------------
Traceback (most recent call last):
File "/Users/zztkm/dev/sandbox/pydev/exception-test/main.py", line 15, in do
print(test[3])
IndexError: list index out of range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/zztkm/dev/sandbox/pydev/exception-test/main.py", line 24, in main
do()
File "/Users/zztkm/dev/sandbox/pydev/exception-test/main.py", line 19, in do
raise MyException(repr(err), "test") from err
MyException: IndexError('list index out of range')
------------
test