Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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.

Matching more general exceptions

The Python exceptions form a class hierarchy. Generally, we match exceptions specifically. In a few cases, we'll use exception superclasses instead of specific classes. Some of the most common superclasses are the...