7

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.

Artur
  • 973
  • 1
  • 14
  • 29
  • Does this answer your question? [Python: Catching specific exception](https://stackoverflow.com/questions/13531247/python-catching-specific-exception) – gdvalderrama Mar 29 '23 at 12:37

1 Answers1

5

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()
trebtac
  • 66
  • 3
  • 1
    Yup, I wanted to avoid ifing for substrings but it seems like that's the only way to work around this problem. Thanks! :) – Artur Jul 12 '19 at 12:05