gpt4 book ai didi

python - 尝试失败时退出函数的最可靠方法

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:32 24 4
gpt4 key购买 nike

排除所有潜在错误的最佳方法是什么?

## Try to...
try:
## Print
print "hi"
## On failure to get data
except Exception:
## Exit out of current function
return

## Try to...
try:
## Print
print "hi"
## On failure to get data
except:
## Exit out of current function
return

或者有更好的方法吗?

提前致谢- Hyflex

最佳答案

通常,始终捕获您知道会发生的特定错误。特别是如果你捕获了所有东西,(即 except:)你将捕获 KeyboardInterrupt 并使你的程序不能被 Ctrl+C 停止; SystemExit 用于杀死一个线程,等等......虽然捕获 Exception 稍微好一点,但它仍然会丢失太多上下文;发生的异常情况可能与您预期不同。因此总是通过它们的名字捕获 IOErrorValueErrorTypeError 等等。

更新

有1种情况要用except Exception;在程序的顶层,或您要确保整个程序不会因未捕获的异常而崩溃的操作。

关于python - 尝试失败时退出函数的最可靠方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18302167/

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