Since C
and D
are subclasses of B
, they are all caught by the except B
clause. When catching exceptions, you need to always list the except
clauses from most to least specific, because your exception is caught by the first one that applies.
From the documentation (emphasis mine):
The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.
The pass
statement is used where a statement is expected, but nothing else is needed. The class
statement cannot have an empty body, but it is often better to use a docstring instead.
class B:
"""An exception that signals an error occurred"""
Syntactically, the docstring fills the need for a statement in the body of the class
statement, but provides additional information as well.