【发布时间】:2017-10-05 11:05:03
【问题描述】:
当我放入 finally 子句时,except 中的 raise 语句不起作用。
所以except 块不会产生Exception。
我错过了什么?如果我想在finally 子句返回值后重新提升Exception 需要做什么?
def test():
res = 1
try:
raise Exception
res = 2
except:
print('ha fallado')
raise
finally:
return res
test()
解决方案:
def test():
res = 1
try:
raise Exception
res = 2
except:
print('ha fallado')
raise
finally:
# ... finally code that need to exec
pass
return res
print(test())
这样,如果发生异常,except块会处理异常然后引发它。
如果没有发生异常,则返回该值。
感谢所有答案!这么快:)
【问题讨论】:
-
return之后你不能再做什么了