Python Python Basics All Together Now Handle Exceptions

David Accomazzo
David Accomazzo
15,982 Points

How would I throw a user-friendly error for the number of tickets not being a string?

Code looks like this so far:

try:
    num_tickets = input("How many tickets would you like, {}?  ".format(name))
    num_tickets = int(num_tickets)
    # Raise a ValueError if the request is for more tickets than are available
    if num_tickets > tickets_remaining:
        raise ValueError('There are only {} tickets remaining.'.format(tickets_remaining))
except ValueError as err:
    # include the error text in the output
    print("Oh no, we ran into an issue. {}. Please try again.".format(err))

How do we throw an error if int(num_tickets) throws a ValueError? I'm not sure what the syntax for that looks like in Python. Currently it just throws the generic error message if num_tickets is a string. I would like to have it throw something like "You must enter a number, not letters, here!"

2 Answers

Steven Parker
Steven Parker
174,098 Points

One way would be to peek at the contents of the message that would be issued, and replace it with a custom message instead:

except ValueError as err:
    if ("invalid literal" in str(err)):
        # use custom message for bad characters
        print("You must enter a number, not letters, here!")
    else:
        # include the error text in the output
        print("Oh no, we ran into an issue.  {}  Please try again.".format(err))