返回::Python 罕见问题集

::-- huangyi [2006-04-22 14:41:38]

::-- ZoomQuiet [2005-09-06 04:10:30]

1. 问:finally子句里面代码是不是总是会被执行?

Q: The code in a finally clause will never fail to execute, right??

What never? Well, hardly ever. The code in a finally clause does get executed after the try clause whether or not there is an exception, and even if sys.exit is called. However, the finally clause will not execute if execution never gets to it. This would happen regardless of the value of choice in the following:

   1 try:
   2     if choice:
   3         while 1:
   4             pass
   5     else:
   6         print "Please pull the plug on your computer sometime soon..."
   7         time.sleep(60 * 60 * 24 * 365 * 10000)
   8 finally:
   9     print "Finally ..."

什么总是?当然,大多数时候是这样的。try子句后面的finally子句的代码确实不管是否发生异常都会被执行,就算调用了sys.exit也一样。但是,如果程序永远也不会运行到那里去,finally子句的代码就不会被执行。比如下面的例子中,不过choice的值是什么都会发生这种情况。

   1 try:
   2     if choice:
   3         while 1:
   4             pass
   5     else:
   6         print "过一会请把您计算机的电源插头拔下来......"
   7         time.sleep(60 * 60 * 24 * 365 * 10000)
   8 finally:
   9     print "Finally ..."

2. 反馈

PyIAQ/Q2 (last edited 2009-12-25 07:09:51 by localhost)