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 Functions and Looping Raising Exceptions

Raise in try block

Is it ok if I move the if and raise within the try block? the code seemed to work fine for me.

import math

def split_check(total_check, number_of_people):  

    return math.ceil(total_check/number_of_people)

    total_check = float(input("Enter the check amount: "))
    number_of_people = int(input("Enter the number of people: "))
    if number_of_people <= 1:  
        raise ValueError ("We can't split the check.")
    amount_due = split_check(total_check,number_of_people)
except ValueError as err:
    print("Please enter a correct amount!")
    print("Each person owns: {}".format(amount_due))

1 Answer

Steven Parker
Steven Parker
215,984 Points

As long as the "raise" occurs within the "try" block, it will work with the "except". That part doesn't matter if it happens inside or outside of the function.

It does make a bit more sense to have it inside the function, because that's where the math is being done.