gpt4 book ai didi

python - 返回和引发异常之间有什么区别吗?

转载 作者:太空狗 更新时间:2023-10-29 21:20:39 24 4
gpt4 key购买 nike

考虑以下代码:

    def f(x):
if x < 10:
return Exception("error")
else:
raise Exception("error2")

if __name__ == "__main__":
try:
f(5) # f(20)
except Exception:
print str(Exception)

有区别吗?什么时候应该使用 return Exception 什么时候应该使用 raise?

最佳答案

raisereturn 是两个本质上不同的关键字。


raise,在其他语言中通常称为 throw,在调用堆栈的当前级别产生错误。您可以通过在 try 中覆盖可能引发错误的区域并在 except 中处理该错误来捕获引发的错误。

try:
if something_bad:
raise generate_exception()
except CertainException, e:
do_something_to_handle_exception(e)
另一方面,

return 将一个值返回到调用函数的位置,因此返回异常通常不是您在这种情况下寻找的功能,因为异常本身不是触发 except 的东西,而是触发它的异常的 raiseing。

关于python - 返回和引发异常之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com