Chapter 12. Exceptions

Table of Contents

12.1. General Mechanism
12.2. Python built-in exceptions
12.3. Raising exceptions
12.4. Defining exceptions

12.1. General Mechanism

Exceptions are a mechanism to handle errors during the execution of a program. An exception is raised whenever an error occurs:

Example 12.1. Filename error

>>> f = open('my_fil')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'my_fil'
An exception can be caught by the code where the error occurred:
	       f = open('my_fil')
	    except IOError, e:
	       print e
Variable e contains the cause of the error:
	    [Errno 2] No such file or directory: 'my_fil'

You could use this exception mechanism to prompt the user in order to get a proper filename.

Example 12.2. Give the user a chance to enter a proper filename

The following program makes a first try with the name of a file provided on the Unix command line. In case of problem, the user is prompted for a valid file name, with the possibility to have a maximum of 3 tries.

import sys

filename = sys.argv[1]
max_tries = 3
tries = 0

while tries < max_tries:
        f = open(filename)
    except IOError, e:
        print e
        tries = tries + 1
        if tries < max_tries:
            filename = raw_input("Enter a filename (%d tries left): " % (max_tries - tries))

if tries == max_tries:
    print "The program needs an existing filename, sorry."

print "Execution of the program proceeds..."
for l in f:
    print l,


If you need to protect your code from more than one error, you can specify several exceptions:

	       y = x / n
	    except ZeroDivisionError, e:
	       print "n is 0", e
	    except OverflowError, e:
	       print "%4.2f / %4.2f raises an overflow!" % (x,n), e