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 ValueError
s 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.