Python:使用2个参数的总和函数的try-except块

发布于 2025-02-07 13:07:27 字数 499 浏览 1 评论 0原文

我有一个总和函数,该函数将两个值作为输入,然后返回总和。但是,如果其中任何一个都不是类型intfloat,我需要提出异常。

我的尝试:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-02-14 13:07:27

以这种方式编写这样的东西的更好形式是:

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

在您称之为此功能的地方使用 try catch

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文