Posts

Showing posts with the label Error Handling

Can I Get The Exception From The Finally Block In Python?

Answer : No, at finally time sys.exc_info is all-None, whether there has been an exception or not. Use: try: whatever except: here sys.exc_info is valid to re-raise the exception, use a bare `raise` else: here you know there was no exception finally: and here you can do exception-independent finalization The finally block will be executed regardless of whether an exception was thrown or not, so as Josh points out, you very likely don't want to be handling it there. If you really do need the value of an exception that was raised, then you should catch the exception in an except block, and either handle it appropriately or re-raise it, and then use that value in the finally block -- with the expectation that it may never have been set, if there was no exception raised during execution. import sys exception_name = exception_value = None try: # do stuff except Exception, e: exception_name, exception_value = sys.exc_info()[:2] raise # or don'...