Matching exception classes in an except clause

In the previous examples, we've shown two kinds of except clauses:

  • except SomeException:
  • except (OneException, AnotherException):

The first example matches a single specific exception. The second example matches any of the exceptions in the list of specific exceptions.

In many cases, the details of the exception are not important. On the other hand, there are some cases where we want to do some processing on the exception object's arguments. We can have the exception object assigned to a variable using this syntax:

except SomeException as exc:

This will assign the exception instance to the exc variable. We can then write this to a log, or examine the arguments, or modify the traceback that gets printed. ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.