How to except the unexpected?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Mar 4 05:41:53 CET 2006


On Sat, 04 Mar 2006 00:10:17 +0100, Rene Pijlman wrote:

> I've writen an application that uses urllib2, urlparse, robotparser and
> some other modules in the battery pack. One day my app failed with an
> urllib2.HTTPError. So I catch that. But then I get a urllib2.URLError, so
> I catch that too. The next day, it encounters a urllib2.HTTPError, then a
> IOError, a socket.timeout, httplib.InvalidURL,...
> 
> How do you program robustly with these modules throwing all those
> different (and sometimes undocumented) exceptions at you?

How robust do you want to be? Do you want to take a leaf out of Firefox
and Windows XP by generating an error report and transmitting it back to
the program maintainer?

> A catchall seems like a bad idea, since it also catches AttributeErrors
> and other bugs in the program.

ExpectedErrors = (URLError, IOError)
ErrorsThatCantHappen = (LookupError, ArithmeticError, AssertionError)

try:
    process_things()
except ExpectedErrors:
    recover_from_error_gracefully()
except ErrorsThatCantHappen:
    print "Congratulations! You have found a program bug!"
    print "For a $327.68 reward, please send the following " \
    "traceback to Professor Donald Knuth."
    raise
except:
    print "An unexpected error occurred."
    print "This probably means the Internet is broken."
    print "If the bug still occurs after fixing the Internet, " \
    "it may be a program bug."
    log_error()
    sys.exit()



-- 
Steven.




More information about the Python-list mailing list