【发布时间】:2015-09-18 04:55:13
【问题描述】:
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 中的异常。
【问题讨论】:
-
它被抓住了。然后你打印出来了。
-
我在问为什么 try 块中的异常没有被捕获。如果它被捕获,那么最后一条语句将打印 0 而不是“整数除法或模除以零”
-
这就是我要问的。为什么不打印 0。
-
你的例子有点难以理解。考虑将其缩小到类似
try: try: raise Exception("first"); finally: raise Exception("second"); except Exception as e: print(e);。
标签: python finally try-except