Next: The Exception Hierarchy
Up: Exceptions
Previous: Tracebacks
  Contents
Although it is often common to have just a few statements as part of a try/except
clause, you may want to run a larger section of code in such a clause, and then organize all
the exception handling after that block of code. As a simple example, suppose we have a
dictionary, mapping user's names to the location of a file with information about the user.
Given a user's name, our program will look up the file name in the dictionary, and then
print the file. In the course of doing this, two different exceptions may arise. First, if
the user is not in the dictionary, then a KeyError exception will be raised; if the
file can't be open, then an IOError exception will be raised. First, here's a code
fragment that catches both of these errors in a single except clause:
userdict = {'john':'/home/john/infofile',
'sue':'/users/sue/sue.info',
'fred':'/home/fred/info.fred'}
user = 'joe'
try:
thefile = userdict[user]
print open(thefile).read()
except (KeyError,IOError):
sys.stderr.write('Error getting information for %s\n' % user)
Alternatively, each exception can be dealt with individually.
try:
thefile = userdict[user]
print open(thefile).read()
except KeyError:
sys.stderr.write('No information for %s is available\n' % user)
except IOError,msg:
sys.stderr.write('Error opening %s: %s\n' % (thefile,msg)
When you use multiple except clauses, Python will execute the code in the
first clause it encounters for which that exception is true, and then execute the
code after the entire try/except construction.
Notice that any exception other than a KeyError or IOError will be handled
in the usual way, namely Python will print a traceback and exit. You can catch all types
of errors by including an except statement with no exception name, but this
practice should generally be avoided, since all exceptions, including syntax errors,
incorrect function calls and misspelled variable names, will be trapped by such a
statement. In general,
different errors need different remedies, and part of proper exception handling consists
of determining exactly what should be done when different errors are encountered.
Next: The Exception Hierarchy
Up: Exceptions
Previous: Tracebacks
  Contents
Phil Spector
2003-11-12