Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 790
Goutham Avatar asked Oct 23 '09 05:10

Goutham


People also ask

What is finally block in Python 3?

Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Example: Let’s try to throw the exception in except block and Finally will execute either exception will generate or not Python3

What is TRY EXCEPT block in Python?

try…except blocks swiftly debug your Python code, a program attempts to execute the code in a “try” block. If this fails, the “except” block executes. The code in a “finally” statement processes regardless of an “except” block.

What happens if there is an exception in the finally block?

Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. If the "finally" block is being executed after an exception has occurred in the try block, and if that exception is not handled. and if the finally block throws an exception.

What happens when you throw an exception in Python?

In other words, this is generic for exceptions. When an exception is thrown in a try block, the interpreter looks for the except block following it. It will not execute the rest of the code in the try block. Python Exceptions are particularly useful when your code takes user input.


1 Answers

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 
like image 64
Alex Martelli Avatar answered Oct 19 '22 21:10

Alex Martelli