finally and rethowing of exception in except, raise in python

Question:

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?

Asked By: Maran Manisekar

||

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.

Answered By: vaultah