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 (2015) Logic in Python Try and Except

can't solve my task

Can't use try ,except,else in the proper place

trial.py
def add(num1,num2):
    try:
    except ValueError:
        return None
    else:
        num1=float(num1)
        num2=float(num2)
        return num1+num2

temp=add(1,2)
print(temp)

1 Answer

Jeffrey James
Jeffrey James
2,636 Points

Here's an example. Yours is missing logic to attempt in the "try" portion of the block. Note the use of finally, which is actually seldom used in the real world, but it's worth knowing about. The type error is raised because the sum function cannot add a string type with an integer.

def add_vals(val1, val2):
  try:
    return sum(val1, val2)
  except TypeError:
    return('You have a type error check your args')
  except ValueError:
    return('You have a value error check your args') 
  finally:
    print('this is always gonna get called')


print(add_vals(1, 'dog'))


>>this is always gonna get called
>>You have a type error check your args