On Fri, 03 Mar 2006 21:10:22 -0800, Paul Rubin wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: >> 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." > > But this isn't good, it catches asynchronous exceptions like the user > hitting ctrl-C, which you might want to handle elsewhere. What you > want is a way to catch only actual exceptions raised from inside the > try block.
It will only catch the KeyboardInterrupt exception if the user actually hits ctrl-C during the time the code running inside the try block is executing. It certainly won't catch random ctrl-Cs happening at other times. The way to deal with it is to add another except clause to deal with the KeyboardInterrupt, or to have recover_from_error_gracefully() deal with it. The design pattern still works. I don't know if it has a fancy name, but it is easy to describe:- catch specific known errors that you can recover from, and recover from them whatever way you like (including, possibly, re-raising the exception and letting higher-level code deal with it); then catch errors that cannot possibly happen unless there is a bug, and treat them as a bug; and lastly catch unexpected errors that you don't know how to handle and die gracefully. My code wasn't meant as production level code, nor was ExpectedErrors meant as an exhaustive list. I thought that was too obvious to need commenting on. Oh, in case this also wasn't obvious, Donald Knuth won't really pay $327.68 for bugs in your Python code. He only pays for bugs in his own code. *wink* -- Steven. -- http://mail.python.org/mailman/listinfo/python-list