Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python catching exception only if message matches

tl;dr
How to catch different exceptions of the same type but with different messages?

Situation
In ideal world I would handle exceptions like this:

try:
    do_something()
except ExceptionOne:
    handle_exception_one()
except ExceptionTwo:
    handle_exception_two()
except Exception as e:
    print("Other exception: {}".format(e))

But external code that I'm using can can throw, in my usage, two exceptions. Both are ValueErrors but have different message. I'd like to differentiate handling them. This is the approach that I tried to take (for easier presentation of my idea I raise AssertionError):

try:
    assert 1 == 2, 'test'
except AssertionError('test'):
    print("one")
except AssertionError('AssertionError: test'):
    print("two")
except Exception as e:
    print("Other exception: {}".format(e))

but this code always goes to the last print() and gives me

Other exception: test

Is there a way to catch exceptions this way? I'm assuming this is possible because Python lets me specify MESSAGE when catching exception ExceptionType('MESSAGE') but in practice I didn't manage to make it work. I also didn't find a definitive answer in the docs.

like image 750
Artur Avatar asked May 26 '26 03:05

Artur


1 Answers

I would go for something like this:

 try:
     do_the_thing()
 except AssertionError as ae:
     if "message A" in ae.value:
        process_exception_for_message_A()
     elif "message B" in ae.value:
        process_exception_for_message_B()
     else:
        default_exception_precessing()
like image 67
trebtac Avatar answered May 30 '26 05:05

trebtac



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!