I have a try
/finally
clause in my script. Is it possible to get the exact error message from within the finally
clause?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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.Just define a blank variable for possible exception before
try
except
block:Tested on Python 3.6
Actually, other answers are bit vague. So, let me clarify it. You can always invoke sys.exc_info() from finally block. However, its output will vary depending whether exception has been actually raised.
Thus, you can always know in finally block, whether exception was raised, if it's first level function. But sys.exc_info() will behave differently when length of call stack exceeds 1, as shown in below example. For more information, refer to How sys.exc_info() works?
I hope, it makes things bit clearer.
No, at
finally
timesys.exc_info
is all-None, whether there has been an exception or not. Use:You'll want to do that in the except clause, not the finally.
Refer to: http://www.doughellmann.com/articles/Python-Exception-Handling/