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

try:            
    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("{}".format(err))
else:
    print("Each person owns: {}".format(amount_due))

1 Answer

Steven Parker
Steven Parker
231,271 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.