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

Isaiah Dicristoforo
Isaiah Dicristoforo
1,135 Points

How 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
Steven Parker
210,933 Points

One 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)
Isaiah Dicristoforo
Isaiah Dicristoforo
1,135 Points

Thanks for your help! I like your approach.

Steven Parker
Steven Parker
210,933 Points

The "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
Bruno Correia
3,114 Points

Steven 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
Bruno Correia
3,114 Points

That's great, thank you!

jaime munoz
jaime munoz
1,438 Points

Great solution thanks!