简体   繁体   English

为什么在python中的“try:”块中的return语句之后执行“finally:”块?

[英]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.按照我的理解:return就是返回一个值的意思。

One example, the python1 script:一个例子,python1 脚本:

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

print fun()  

The output of the script is :脚本的输出是:

98 98

98 98

ok好的

So my question is why the output of the script is not:所以我的问题是为什么脚本的输出不是:

98 98

OK好的

98 98

Why is the output of the OK line at the end?为什么最后是OK行的输出?

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.无论在try块中发生什么, finally块都保证在try块之后执行。 Even if no exception was raised.即使没有引发异常。

finally is generally used to release resources, clean up of variables etc. finally一般用于释放资源、清理变量等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果 finally 块包含 return 语句,为什么除了块内的“return”语句不会静默执行? - Why is a `return` statement inside of except block silently not executed if finally block contains a return statement? 为什么 finally 块中的 return 语句否定了 except 块中的引发? - Why does a return statement in a finally block negates raise in the except block? finally 块在 python 中 try 子句的 break、continue、return 语句之前执行 - finally block execute before the break,continue,return statement of try clause in python 最终会在没有 python 的尝试块的情况下阻止工作吗? - will finally block work without try block in python? Python *与*语句完全等同于尝试 - (除外) - finally块? - Is Python *with* statement exactly equivalent to a try - (except) - finally block? finally 总是在 try 块返回之前运行,那么为什么 finally 块中的更新不会影响 try 块返回的变量的值呢? - Finally always runs just before the return in try block, then why update in finally block not affect value of variable returned by try block? 为什么在IDLE中try / except / finally块之后出现SyntaxError代码错误? - Why SyntaxError for code after the try/except/finally block in IDLE? python在期望异常后返回try块 - python return to try block after expect exception python:如果finally块引发异常,则从try块恢复异常 - python: recover exception from try block if finally block raises exception 从finally块python中的try块中访问变量 - Access variable in try block from finally block python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM