当我加入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
之后,你不能再做任何事情。 - t.m.adam