Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

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.

1 Answer

0 votes
by (25.1k points)

You can do it 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_processing()

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 2, 2019 in Python by ashely (50.2k points)
0 votes
1 answer
asked Nov 25, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Nov 25, 2020 in Python by ashely (50.2k points)

Browse Categories

...