try: #error code except Exception as e: print 'error',e raise miexp("malicious error") #userdefined exception, miexp finally: print 'finally'
Why the output is in the following formats?
Output:
error finally malicious error
Actually I expected as:
error malicious error finally
Why so?
The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
The finally keyword is used in try... except blocks. It defines a block of code to run when the try... except...else block is final.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
Deep dive. No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.
miexp("malicious error")
isn't handled, therefore it will end the execution of the program. On the other hand, the finally
block is guaranteed to be executed.
To ensure this Python executes the finally
block before actually raising the exception. From the documentation:
If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With