0

I have a python program that takes integer only inputs like this:

Valid = False
while not Valid:
    try:
        x = int(Input("enter integer value"))
        Valid = True
    except:
        pass

For easier debugging, I want to be able to terminate the program while it is running by giving an exit command as an input, rather than by killing the terminal, so I wrote this function:

def Input(message):
    x = input(message)
    if x == "exit":
        #something to terminate program
    return x

By my understanding, common options like sys.exit() and os._exit() work by raising a SystemExit exception so they are ignored.

Is there a more definite way of terminating a program without raising an exception?

2
  • 4
    This is why you shouldn't use a bare except. Use the specific exception that you intend to catch (ValueError, in this case), or if you can't narrow it down that far, at least use except Exception:, which excludes SystemExit. Commented May 12, 2024 at 19:04
  • 3
    This is one of the reasons why you should narrow the scope of exceptions you catch. Had you except ValueError, you would get the exception you want without messing up SystemExit. Commented May 12, 2024 at 19:04

1 Answer 1

0

If I understood correctly, os._exit() doesn't raise a SystemExit exception, have you tried using that?

Just don't forget to include the os module: import os

Whereas sys.exit(), as you rightly stated raises an exception.

Sign up to request clarification or add additional context in comments.

1 Comment

From the documentation: "Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork()." It's not just an exception-free alternative to sys.exit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.