Can I get the exception from the finally block in python?

前端 未结 4 884
夕颜
夕颜 2020-12-04 23:56

I have a try/finally clause in my script. Is it possible to get the exact error message from within the finally clause?

4条回答
  •  独厮守ぢ
    2020-12-05 00:21

    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't -- it's up to you
    finally:
        # do something with exception_name and exception_value
        # but remember that they might still be none
    

提交回复
热议问题