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

Viewed 44259

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

5 Answers

No, at finally time sys.exc_info is all-None, whether there has been an exception or not. Use [this instead]: …

The other answerer is correct in that you should be handling this inside the except clause.

However, for posterity / the record, here is an answer to the original question as stated:

import sys
try:
    int("not an integer LOL")
except:
    e = sys.exc_info()[1]
    # isinstance(e, ValueError) == True
    raise # this line is optional; I have it commented for the example output
else:
    e = None # you should do this to avoid a NameError
finally:
    print("I really wanted to access %s inside of a finally clause. And I'm doing so now."
      % repr(e))

This will print something like:

I really wanted to access ValueError("invalid literal for int() with base 10: 'not an integer LOL'") inside of a finally clause. And I'm doing so now.

Related