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?
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 useexcept Exception:, which excludesSystemExit.except ValueError, you would get the exception you want without messing upSystemExit.