简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM