Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics All Together Now Handle Exceptions

"nesting" valueErrors?

So, I'm following along the best I can. The first ValueError was cancelled out when I added the second. This was best method I could come up with so that both still trigger if needed. It works, but is there an easier way to do this or is this a pretty common solution?

TICKET_PRICE = 10

tickets_remaining = 100  

while tickets_remaining >= 1:
    print("There are {} tickets remaining.".format(tickets_remaining))
    name = input("What's your name?  ")
    num_tickets = input("Ok {}, how many tickets would you like to purchase?  ".format(name))
    try:
        num_tickets = int(num_tickets)
    except ValueError:
        print("Oh no, we ran into an issue. Only numbers are allowed. Please try Again.")
    else:                      
        try:
            if num_tickets > tickets_remaining:
                raise ValueError(f"There are only {tickets_remaining} tickets remaining.")
        except ValueError as err:
            print(f"Oh no, we ran into an issue. {err}. Please try again.")
        else:
            amount_due = num_tickets * TICKET_PRICE
            print(f"Your total is ${amount_due}.")
            should_proceed = input("Do you want to proceed? Y/N?  ")
            if should_proceed.lower() == "y":
                #TODO: Gather credit card info and process it.
                print("Sold!")
                tickets_remaining -= num_tickets
            else:
                print("Thank you for stopping by {}.".format(name))
print("Sorry, the tickets are sold out.")
Thomas Greer
Thomas Greer
1,472 Points

I ran into the same issue. Though, I struggled to resolve it on my own. Your solution fixed my problem, but I do feel there is a cleaner approach. I would love for someone to show their solution.

1 Answer

Steven Parker
Steven Parker
231,275 Points

You don't have to create a nested "try" block to make a test that raises an exception and then catches it. You can just handle your test condition directly as part of the test code body, which is probably a bit more common (and more compactly coded) approach.