python这个函数如何到达第10行

2024-04-19 20:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望myfunction返回0而不执行finally,但为什么会这样呢

def myfunction(i):
    try:
        result=10/i
    except:
        return 0
    finally:
        return 10 

print(myfunction(0))

Tags: returndefresultprinttryexceptmyfunctionfinally
3条回答

它返回10,因为try块中的finally子句在任何return语句之前执行,如this answer

另外值得注意的是,您使用的是泛型except,这将导致许多意外行为。检查this answer以了解如何最佳构造try/except块和最佳raise异常

^{}始终执行,无论是否发生异常。文件在本质上非常清楚:

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.

所以finally子句中的return语句覆盖了exception子句中的语句。将return语句放在finally子句中没有多大意义,因为这是函数返回的唯一值

无论catch块中发生什么,finally部分中的代码都将运行(程序在到达finally部分之前以某种方式终止的时间除外),如果您不想让它运行,您应该如下更改代码:

def myfunction(i):
    try:
        result=10/i
    except:
        return 0
    return 10

相关问题 更多 >