【发布时间】:2020-07-28 13:23:47
【问题描述】:
这是代码:
def funcFail():
try:
raise Exception("Failed externally")
print("Should not print")
except Exception as e:
print(f"Exception : {e}")
raise Exception(f"Exception in occured due: {e}")
finally:
return "This is finally block :P"
print("This is finally block :P")
def checkexpcep():
global k
k = []
try:
funcFail()
except Exception as e:
print(f"Exception out : {e}")
k.append(str(e))
finally:
return "nothing"
checkexpcep()
预期:
"Exception : Failed externally"
"This is finally block :P"
"Exception out : Exception in occured due: Failed externally"
输出:
"Exception : Failed externally"
【问题讨论】:
-
显然
return中的finallyswallows例外。 -
@quamrana,有没有其他选择,或者我应该在没有 finally 的情况下继续吗?
-
我还建议使用自定义异常,可能会使这样的代码更容易调试:docs.python.org/3/tutorial/errors.html#user-defined-exceptions
-
你应该使用
finally来整理是否有异常。只有在没有异常的情况下要返回东西时才使用return <something>,所以看起来return与finally格格不入。
标签: python exception raiserror