Bookmark and Share

When working with Python, sometimes, more than anything else, you need to know what went wrong. Quite aside from all the debate about what you should do in response, and particularly when developing, you need more than just a vague idea that your CGI bailed and that there might (or might not) be some usable indication of this in the system web logs.

Even when working in a pure command line context, you may need to catch anything and everything. If you do, the following gives you a basic model of just how to do it.

import sys try: a = 5 / 0 except Exception,e: # the Exception class provides messages print 'Exception caught, message: '+str(e) raise SystemExit # bail out (optional) except: # other exceptions e = sys.exc_info() # so we mine sys library info instead print 'Non-Exception class Exception caught, message: '+str(e) raise SystemExit # bail out (optional) else: # and, well, sometimes things work out. print 'it worked, no exception!' # whoo hoo... finally: # always happens print 'Glad THAT ordeal is over -- one way or another.' print 'And here we are. Aren't we?' # you only get here if things worked out

Try out the above with code you know will work, like a=1 immediately subordinate to the try: clause, and then with code you know won’t work, like a=5/0 and see what it does.

Something to keep in mind: The ELSE clause of a TRY block only runs if execution proceeds off the end of the TRY section. So if you have two statements in the TRY section, and the first one runs but the second one does not, the ELSE clause will not execute. The EXCEPT clause will due to the exception. FINALLY always, always runs, even if the EXCEPT clause has an exit in it.

You can think of the ELSE as being functionally equivalent to just putting code right after the TRY-EXCEPT-ELSE-FINALLY sequence if you build an unavoidable exit into the EXCEPT portion. Of course, it’s nice to put related code in, because that makes the functionality and intent more obvious. And if you don’t have an exit there… then ELSE can be quite useful, as it won’t run if the TRY block fails, but the code after the entire TRY-EXCEPT-ELSE-FINALLY sequence will.

Hope someone finds this useful. Took me a while to dig through it all and wrap my head around even the basic idea that sometimes, you just need to know!