exit(0) within try block not exiting the program

huangapple go评论44阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月26日 21:47:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定