A well-written program should produce valuable results even when
exceptional conditions occur. A program depends on numerous resources:
memory, files, other packages, input-output devices, to name a few.
Sometimes it is best to treat a problem with any of these resources as an
exception, which interrupts the normal sequential flow of the
program.
An exception is an event that interrupts
the ordinary sequential processing of a program. When an exception is
raised, Python will handle
it immediately. Python does this by examining
except
clauses associated with
try
statements to locate a
suite of statements that can process the exception. If there is no
except
clause to handle the exception, the program
stops running, and a message is displayed on the standard error
file.
An exception has two sides: the dynamic change to the sequence of
execution and an object that contains information about the exceptional
situation. The dynamic change is initiated by the
raise
statement, and can finish with the handlers
that process the raised exception. If no handler matches the exception,
the program's execution effectively stops at the point of the
raise
. In addition to the dynamic side of an
exception, an object is created by the
raise
statement; this is used to carry any information associated with the
exception.
Consequences. The use of exceptions has a two important consequences. First,
we need to clarify where exceptions can be raised. Since various
places in a program will raise exceptions, and these can be hidden
deep within a function or class, their presence should be announced by
specifying the possible exceptions in the docstring. Second, multiple
parts of a program will have handlers to cope with various exceptions.
These handlers should handle just the meaningful exceptions. Some
exceptions (like RuntimeError
or
MemoryError
) generally can't be handled
within a program; when these exceptions are raised, the program is so
badly broken that there is no real recovery.
Exceptions are a powerful tool for dealing with rare, atypical
conditions. Exceptions should be considered as different from the
expected or ordinary conditions that a program handles. For example, if
a program accepts input from a person, exception processing is not
appropriate for validating their inputs. There's nothing rare or
uncommon about a person making mistakes while attempting to enter
numbers or dates. On the other hand, an unexpected disconnection from a
network service is a good candidate for an exception; this is a rare and
atypical situation. Examples of good exceptions are those which are
raised in response to problems with physical resources like files and
networks.
Python has a large number of built-in exceptions, and a programmer
can create new exceptions. Generally, it is better to create new
exceptions rather than attempt to stretch or bend the meaning of
existing exceptions.