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

Why not use "if" instead of an exception block

What's the advantage of using an Exception when a simple "if, else" could work? I wrote an alternate of the code in the video with using "if" to check for num_tickets > tickets_remaining and it works. The first and last part of the code are identical to the one in the video (didn't include them to highlight only the part I'm changing)

# First part of the code......

try:
        num_tickets = int(num_tickets)
    except ValueError as err:
        print("There is an issue. {}. try again".format(err))
    else :
        if num_tickets > tickets_remaining :
            print ("not enough tickets.")
        else :
            total_price = num_tickets * TICKET_PRICE

# ...last part of the code

[MOD: added ```python formatting -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Hey Niusha Viliani! Good question. Your solution is valid.

Using ValueError is has the minor advantage of grouping the error conditions together for readability. It also allows showing off how to use the passed error text in a print statement.

To further readability, one could define a specific User-defined Exception such as ZeroTicketError to indicate no tickets available.

However, since a ValueError is defined as...

exception ValueError

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

...it works well enough.

Post back if you need more help. Good luck!!!