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 trialIsaiah Dicristoforo
1,135 PointsHow do we print out separate error messages for each exception?
In the video, we have a single except block to catch both value errors. If the user does not enter a number, our except block prints a confusing message. If we enter a ticket number greater than the total tickets available, we raise an exception and print out a custom error message. How would we catch each ValueError separately, and print out a descriptive message for each?
5 Answers
Steven Parker
231,172 PointsOne idea is to detect the system messages by their content, and issue a custom replacement. For example:
except ValueError as err:
if "invalid literal for int" in err: # substitute this confusing message
print("Sorry, but you must enter a number!")
else: # otherwise print what we got
print(err)
Steven Parker
231,172 PointsThe "as" variable is an exception object, which contains the string you passed in. It has a "__str__" override that will return that string if the object is accessed as a string.
Bruno Correia
3,114 PointsSteven Parker I tried that but ran into a different TypeError that says that ValueError is not iterable. After checking online I could fix it by changing the code to
if "invalid literal for int" in str(err):
but now I'm confused. Isn't err a string already since it's passed the text that comes from ValueError?
If it helps, this is what I got at first when not using str(err)
Traceback (most recent call last):
File "masterticket.py", line 12, in <module>
num_tickets = int(num_tickets)
ValueError: invalid literal for int() with base 10: 'blue'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "masterticket.py", line 17, in <module>
if "invalid literal for int" in err:
TypeError: argument of type 'ValueError' is not iterable
Bruno Correia
3,114 PointsThat's great, thank you!
jaime munoz
1,438 PointsGreat solution thanks!
Isaiah Dicristoforo
1,135 PointsIsaiah Dicristoforo
1,135 PointsThanks for your help! I like your approach.