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.