gpt4 book ai didi

python - try 和 except 都引发异常。

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:20 24 4
gpt4 key购买 nike

def FancyDivide(list_of_numbers, index):
try:
try:
raise Exception("0")
finally:
denom = list_of_numbers[index]
for i in range(len(list_of_numbers)):
list_of_numbers[i] /= denom
except Exception, e:
print e

调用函数时,我得到以下输出。

FancyDivide([0, 2, 4], 0)
integer division or modulo by zero

在 try 代码中引发了异常。在finally中也有异常。为什么捕获到finally中的异常而不是try中的异常。

最佳答案

来自documentation -

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 a except or else clause), it is re-raised after the finally clause has been executed.

(强调我的)

如前所述,异常 - Exception("0") 只会在完成 finally block 后再次引发。但是因为在 finally block 中发生了异常,所以它被引发而不是 Exception("0")

关于python - try 和 except 都引发异常。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32644126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com