Exceptions - Page 2
September 14, 2001
Exceptions indicate errors and break out of the normal control
flow of a program. An exception is raised using the
raise statement. The general format of the
raise statement is raise exception [, value
] where exception is the exception type and
value is an optional value giving specific details
about the exception. For example:
raise RuntimeError, Unrecoverable Error
If the raise statement is used without any arguments, the last
exception generated is raised again (although this works only
while handling a previously raised exception).
To catch an exception, use the try and
except statements, as shown here:
try:
f = open('foo')
except IOError,e:
print "Unable to open 'foo':", e
When an exception occurs, the interpreter stops executing
statements in the try block and looks for an
except clause that matches the exception that has
occurred. If found, control is passed to the first statement in
the except clause. Otherwise, the exception is
propagated up to the block of code in which the try
statement appeared.This code may itself be enclosed in a
try-except that can handle the exception. If an
exception works its way up to the top level of a program without
being caught, the interpreter aborts with an error message. If
desired, uncaught exceptions can also be passed to a user-defined
function sys.excepthook() as described in Appendix
A,"The Python Library," sys module.
The optional second argument to the except statement
is the name of a variable in which the argument supplied to the
raise statement is placed if an exception occurs.
Exception handlers can examine this value to find out more about
the cause of the exception.
Multiple exception-handling blocks are specified using multiple
except clauses, such as in the following example:
try:
do something
except IOError,e:
# Handle I/O error
...
except TypeError,e:
# Handle Type error
...
except NameError,e:
# Handle Name error
...
A single handler can catch multiple exception types like this:
try:
do something
except (IOError,TypeError,NameError),e:
# Handle I/O,Type, or Name errors
...
To ignore an exception, use the pass statement as
follows:
try:
do something
except IOError:
pass # Do nothing (oh well).
To catch all exceptions, omit the exception name and value:
try:
do something
except:
print 'An error occurred '
Control Flow - Page 1
Python Essential Reference, Second Edition
Built-in Exceptions - Page 3
|