I can raise an exception from another exception in order to provide additional information, e.g.:
try:
age = int(x)
except Exception as ex:
raise ValueError("{} is not a valid age.".format(x)) from ex
Is there any way to source from multiple exceptions? e.g.
try:
age = int(x)
except Exception as ex1:
try:
age = date_now().year - parse_date(x).year
except Exception as ex2:
raise ValueError("{} is not a valid age or date.".format(x)) from ex1 + ex2
An earlier exception that causes an exception currently being handled is stored in the __context__ attribute of the current exception object, while the exception explicitly specified in the from of the raise statement is stored as the __cause__ attribute, per the specifications of PEP 344 – Exception Chaining and Embedded Tracebacks:
For an explicitly chained exception, this PEP suggests
__cause__because of its specific meaning. For an implicitly chained exception, this PEP proposes the name__context__because the intended meaning is more specific than temporal precedence but less specific than causation: an exception occurs in the context of handling another exception.
Both __cause__ and __context__ are formatted properly in the traceback report, so the following code:
from datetime import datetime
x = 'foo'
try:
age = int(x)
except ValueError:
try:
age = datetime.now().year - datetime.fromisoformat(x).year
except ValueError as e:
raise ValueError(f'{x} is not a valid age or date.') from e
would produce the following traceback with all the exception sources properly noted:
Traceback (most recent call last):
File "./prog.py", line 5, in <module>
ValueError: invalid literal for int() with base 10: 'foo'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
ValueError: Invalid isoformat string: 'foo'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "./prog.py", line 10, in <module>
ValueError: foo is not a valid age or date.
Demo: https://ideone.com/icdd8K
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With