简体   繁体   中英

Why "finally:" block is executed after the return statement in a "try:" block in python?

According to my understanding:return is the meaning of returning a value.

One example, the python1 script:

def func():  
    try:  
       print 98  
       return 'ok' 
    finally: 
       print 98  

print fun()  

The output of the script is :

98

98

ok

So my question is why the output of the script is not:

98

OK

98

Why is the output of the OK line at the end?

Because when you use

try:
  #some code
finally:
  #some other code

the finally block is guaranteed to be executed after the try block no matter what happens in the try block. Even if no exception was raised.

finally is generally used to release resources, clean up of variables etc.

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