Exception Objects
Exceptions are instances of subclasses of the built-in, legacy-style Exception
class.[4] An instance of any subclass of Exception
has an attribute args
, the tuple of arguments used to create the instance. args
holds error-specific information, usable for diagnostic or recovery purposes. In Python 2.5, class Exception
is new-style, since it inherits from the new built-in new-style class BaseException
; this, in turn, makes all built-in exception classes new-style in Python 2.5. For detailed explanations of how the standard exception hierarchy changes in 2.5, and how things will move further in 3.0, see http://python.org/doc/peps/pep-0352/.
The Hierarchy of Standard Exceptions
All exceptions that Python itself raises are instances of subclasses of Exception
. The inheritance structure of exception classes is important, as it determines which except
clauses handle which exceptions. In Python 2.5, however, classes KeyboardInterrupt
and SystemExit
inherit directly from the new class BaseException
and are not subclasses of Exception
: the new arrangement makes it more likely that a general handler clause coded as except Exception:
does what’s intended, since you rarely want to catch KeyboardInterrupt
and SystemExit
(exception handlers are covered in try/except).
In Python 2.3 and 2.4, the SystemExit
, StopIteration
, and Warning
classes inherit directly from Exception
. Instances of SystemExit
are normally raised by the exit
function in module sys
(covered in exit
in The sys ...
Get Python in a Nutshell, 2nd Edition 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.