I have a sum function which takes two values as input, and returns the sum. However, I need to raise an exception if either one of them is not of type int
or float
.
My attempt:
def add(a, b):
try:
return a+b
except:
raise TypeError("{0} is invalid".format(a))
except:
raise TypeError("{0} is invalid".format(b))
returns:
SyntaxError: default 'except:' must be last
Is return
in the wrong place?
the better form of writing such a thing is in this way:
def add(a, b):
if type(a) != int and type(a) != float:
raise TypeError("{0} is invalid".format(a))
if type(b) != int and type(b) != float:
raise TypeError("{0} is invalid".format(b))
return a+b
and use try and catch in where you call this function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.