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:

    f = open('foo') 
except IOError, e: 
    print "Unable to open 'foo': ", e 

When an exception occurs, the interpreter stops ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.