python 如果最终 returns 值未引发异常
python exception not raised if finally returns value
谁能解释为什么下面的例子没有引发 Exception
?
def foo():
try:
0/0
except Exception:
print('in except')
raise
finally:
print('in finally')
return 'bar'
my_var = foo()
print(my_var)
这只是 returns:
in except
in finally
bar
因为没有 return 'bar'
语句的相同代码抛出异常:
in except
in finally
Traceback (most recent call last):
File "test.py", line 10, in <module>
my_var = foo()
File "test.py", line 3, in foo
0/0
ZeroDivisionError: division by zero
有关详细信息,请参阅 ,但简而言之
应该始终执行 finally
块,因此 Python 必须忽略 raise
语句,因为这会违反语义
谁能解释为什么下面的例子没有引发 Exception
?
def foo():
try:
0/0
except Exception:
print('in except')
raise
finally:
print('in finally')
return 'bar'
my_var = foo()
print(my_var)
这只是 returns:
in except
in finally
bar
因为没有 return 'bar'
语句的相同代码抛出异常:
in except
in finally
Traceback (most recent call last):
File "test.py", line 10, in <module>
my_var = foo()
File "test.py", line 3, in foo
0/0
ZeroDivisionError: division by zero
有关详细信息,请参阅 ,但简而言之
应该始终执行 finally
块,因此 Python 必须忽略 raise
语句,因为这会违反语义