O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required