A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed.
它返回
10
,因为try
块中的finally
子句在任何return
语句之前执行,如this answer另外值得注意的是,您使用的是泛型
except
,这将导致许多意外行为。检查this answer以了解如何最佳构造try/except
块和最佳raise
异常^{} 始终执行,无论是否发生异常。文件在本质上非常清楚:
所以
finally
子句中的return
语句覆盖了exception
子句中的语句。将return
语句放在finally
子句中没有多大意义,因为这是函数返回的唯一值无论catch块中发生什么,finally部分中的代码都将运行(程序在到达finally部分之前以某种方式终止的时间除外),如果您不想让它运行,您应该如下更改代码:
相关问题 更多 >
编程相关推荐