英文:
exit(0) within try block not exiting the program
问题
我正在尝试在满足条件时退出程序。条件位于一个 try
块中。
以下是我的代码:
import time
a = 1
while True:
time.sleep(2)
try:
if a == 1:
print("exiting")
exit(0)
else:
print("in else")
except:
print("in except")
但是它没有退出,而是打印了以下内容:
exiting
in except
exiting
in except
exiting
in except
exiting
in except
.
.
.
有什么解释吗?
英文:
I am trying to exit the program if a condition has been met. The condition is in a try
block.
Here is my code:
import time
a=1
while True:
time.sleep(2)
try:
if a==1:
print("exiting")
exit(0)
else:
print("in else")
except:
print("in except")
instead of exiting it is printing:
exiting
in except
exiting
in except
exiting
in except
exiting
in except
.
.
.
Any explanation?
答案1
得分: 1
不要抓取所有异常,因为有时可能会导致意外行为并掩盖真正的问题。
话虽如此,你的代码问题在于 exit(0)
引发了一个 SystemExit
异常,这个异常被你的代码中的裸露 except
无意中处理了。如果你真的想抓取所有异常,可以考虑修改你的代码如下:
try:
...
except SystemExit:
raise
except Exception:
# 处理
这将处理除了由 exit(0)
引发的异常之外的所有异常。
英文:
It's not a good idea to catch all exceptions, as it sometimes may lead to unexpected behaviour and disguise real issues.
Having said that, the problem with your code is that exit(0)
raises a SystemExit
exception, that is inadvertently handled by the bare except
in your code. If you really want to catch all exceptions, you can consider modifying your code like so:
try:
...
except SystemExit:
raise
except Exception:
# handling
This should handle all exceptions except the one raised by exit(0)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论