Orpha Mortimer
Orpha Mortimer

Reputation: 13

Exit program without triggering exception handling

I wasn't really sure how to title my question, but my issue is this; I have my program set up to guess a number and handle exceptions. The program loops until the number is guessed, but when the program exits, my exception message shows at the same time. How can I fix this?

num = None
while num != 31:
    try:
        num = int(input("What is the age of my creator? \n"))
        if num < 31:
            print("Higher! Guess again! \n")
        elif num > 31:
            print("Lower! Guess again! \n")
        elif num == 31:
            print("Good Guess!")
            exit()
    except:
        print("Numbers only! \n")

This is my output:

What is the age of my creator? 31 Good Guess! Numbers only!

Process finished with exit code 0

Upvotes: 0

Views: 613

Answers (1)

cs95
cs95

Reputation: 403050

If you want to keep the exception message, I would recommend a break instead of exit, for a more natural exit from your program. Try this:

try:
    ...
    elif num == 31:
        print("Good Guess!")
        break
except ValueError:
    print("Numbers only! \n")

Also, you should catch a specific error rather than a catch-all bare except.


If you want to silence any error messages, you should use pass instead. From the docs:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

try:
    ...
except ValueError:
    pass

pass is an innocuous placeholder statement that does nothing.


Upvotes: 1

Related Questions