next up previous contents
Next: Raising Exceptions Up: Exceptions Previous: Dealing with Multiple Exceptions   Contents

The Exception Hierarchy

When you have several except clauses as part of a try/except construct, and an exception is raised, the statements after the first except clause which is matched will be executed. Usually this will not cause any surprises, but there is a hierarchy of exceptions in Python so that exceptions higher in the hierarchy will be activated even though they are not an exact match for the exception that has been raised. For example, the EnvironmentError exception will catch both IOErrors and OSErrors. Thus, when you create try/except clauses in your programs, the ordering of the exceptions may affect they way that their corresponding code is called. Continuing with the EnvironmentError example, if an except clause for an OSError appeared after an except clause for an EnvironmentError within the same try/except construction, the OSError clause would never be activated, since the EnvironmentError would intercept the exception, and only one exception per try/except construct will ever be activated. On the other hand, if the EnvironmentError clause appeared after the OSError clause, it would be activated when an IOError was raised, since that exception is below EnvironmentError in the exception hierarchy. Figure 9.1 illustrates the hierarchy; exceptions which are indented below other exceptions will be caught by the less indented exception as well as through their own names.

Figure 9.1: Exception Hierarchy
\begin{figure}\footnotesize\renewedcommand{labelitemi}{}\renewedcommand{labelite...
...r}
\item
\texttt{ValueError}
\end{itemize}\end{itemize}\end{itemize}\end{figure}


next up previous contents
Next: Raising Exceptions Up: Exceptions Previous: Dealing with Multiple Exceptions   Contents
Phil Spector 2003-11-12