下面是代码:
def fancy_divide(list_of_numbers, index):
try:
try:
raise Exception("0")
finally:
denom = list_of_numbers[index]
for i in range(len(list_of_numbers)):
l ist_of_numbers[i] /= denom
except Exception as ex:
print(ex)如果我调用:
fancy_divide([0, 2, 4], 0)为什么它不打印出'0‘?
如果我像这样编辑代码:
def fancy_divide(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 as ex:
raise Exception("0")
print(ex)然后调用同样的东西,它会打印:
Traceback (most recent call last):
File "<ipython-input-16-c1b0ac98281c>", line 1, in <module>
fancy_divide([0, 2, 4], 0)
File "/Users/dsn/.spyder-py3/temp.py", line 10, in fancy_divide
raise Exception("0")
Exception: 0为什么会这样呢?使用raise的正确方式是什么?
发布于 2018-01-25 11:58:36
您的finally块本身正在引发一个异常,一个被零除的错误(因为您的分母是0)。如果finally块在异常冒泡时执行,并引发自己的异常,则它会:
Python2上的
您的其他代码打印回溯,因为您根本没有捕捉到您引发的第二个异常(并且它绕过了您的print)。
我建议reading the exception tutorial理解更多;您的示例代码是如此人为/毫无意义,以至于不可能说出您真正有什么误解,以及什么只是为了说明一个特定的行为来支持您的问题。
发布于 2018-01-25 12:20:23
def fancy_divide(list_of_numbers, index):
try:
try:
raise Exception("0") # 1
finally:
denom = list_of_numbers[index]
for i in range(len(list_of_numbers)):
list_of_numbers[i] /= denom
except Exception as ex:
print(ex) # 2注意这些数字
1.这件事首先在第二个try外部触发except块,而忽略其他块。
2.这将被触发,因为try块中有一个异常。
在except块中使用raise来避免复杂的事情。
我会将你的代码重写为:
def fancy_divide(list_of_numbers, index):
try:
# Your fancy divide logic here
except Exception as ex:
raise Exception('Something went wrong: {exception}'.format(exception=ex))
finally:
# Don't need tohttps://stackoverflow.com/questions/48435358
复制相似问题