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 trialRoger Hauber
1,206 PointsTwo different ValueErrors in try block
So I'm slightly confused: in the example solution we have two different kinds of ValueError that can occur in the try block. Either a coercion ValueError because the input cannot be coerced to int() or the ValueError resulting from the tickets purchased being higher than the remaining tickets. By adding err to the print() statement in the except block, it works fine with our custom error message in the latter case, but in the coercion case it now displays the original user-unfriendly error message. How can I customize both error messages separately?
1 Answer
Megan Amendola
Treehouse TeacherHi! In the try block, the as err
should print out the err message attached to the error.
try:
# first test
num_tickets = int(num_tickets)
# second test
if num_tickets > tickets_remaining:
raise ValueError('There are only {} tickets remaining'.format(tickets_remaining)
except ValueError as err:
print('Oh no we ran into a problem. {}. Please try again.'.format(err))
If the first test fails, then a message like invalid literal for int() with base 10
should be added to the 'Oh no' message as the error. If the second test fails, it should add the There are only...
message to 'Oh no'. Like this:
>>> How many tickets do you want? tree
Oh no we ran into a problem. invalid literal for int() with base 10: 'tree'. Please try again.
>>> How many tickets do you want? 10000
Oh no we ran into a problem. There are only 100 tickets remaining. Please try again.
Nelson Pang
2,229 PointsNelson Pang
2,229 PointsMegan, I see how the code runs and understand your explanation - however, I think what Roger is asking and what I'm curious of also is what if when the user enters a non-number we don't want the output to say
invalid literal for int() with base 10: 'tree'
but INSTEAD say something more "user friendly" as is the goal likeWe need a number of tickets, not a word
. So for example, a result that looks like this:I've tried fiddling around with the code to achieve this, but seem to be breaking it right now. With a little more time I think I'll get it!
EDIT: Aha! Looks like I found what I was looking for! Should've searched harder