Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics All Together Now Handle Exceptions

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
212,260 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))

Sounds good to me! Thanks