Python:使用2个参数的总和函数的try-except块
我有一个总和函数,该函数将两个值作为输入,然后返回总和。但是,如果其中任何一个都不是类型int
或float
,我需要提出异常。
我的尝试:
def add(a, b):
try:
return a+b
except:
raise TypeError("{0} is invalid".format(a))
except:
raise TypeError("{0} is invalid".format(b))
返回:
SyntaxError: default 'except:' must be last
是错误的位置返回
吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以这种方式编写这样的东西的更好形式是:
在您称之为此功能的地方使用 try 和 catch
the better form of writing such a thing is in this way:
and use try and catch in where you call this function