0

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?

sovon
  • 877
  • 2
  • 12
  • 28
  • 2
    You're trapping all exceptions, including the `SystemExit` exception, so your code never exits. Never use bare `except` statements. – larsks Jun 26 '23 at 13:52
  • You can see the exceptions. `import sys` then in your print, `print(sys.exc_info())` – matt Jun 26 '23 at 14:05
  • Does this answer your question? [python sys.exit not working in try](https://stackoverflow.com/questions/25905923/python-sys-exit-not-working-in-try) – matt Jun 26 '23 at 14:22

1 Answers1

1

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)

Aditya Singh
  • 332
  • 2
  • 12