Catch multiple exceptions in an except clause in Python

When using try except blocks to catch exceptions, we mostly catch one exception in an except clause and process it. However some time we may not need that kind of separate treatment for each exception. Instead, some time you may need to treat multiple exceptions in the same way. In such situations you can use more than one exception in a single except clause. You have to specify the except keywords inside a parenthesis separated by comma. Here is the syntax.

try:
    ...
    ...
    ...
except (OSError, ValueError) as err:
    print("Error: {0}".format(err))
except:
    print("Unexpected error:")
    raise

See more Python tips.

Reference

Related Articles & Tools

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.