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

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......

        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
Chris Freeman
Treehouse Moderator 67,982 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!!!