Exceptions

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 ...

Get Python: Essential Reference, Third 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.