Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. Raise exception from multiple exceptions

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
like image 491
c z Avatar asked Aug 15 '26 12:08

c z


1 Answers

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

like image 188
blhsing Avatar answered Aug 18 '26 03:08

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!