Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finally and rethowing of exception in except, raise in python

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?

like image 559
Maran Manisekar Avatar asked Dec 13 '15 08:12

Maran Manisekar


People also ask

What is difference between Except and finally in Python?

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.

Can finally be used with except in Python?

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.

How do you raise exceptions in except Python?

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.

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

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.


1 Answers

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.

like image 136
vaultah Avatar answered Sep 24 '22 15:09

vaultah