【问题标题】:What exception to raise for testcase: string length > value? - Python为测试用例引发什么异常:字符串长度>值? - Python
【发布时间】:2018-03-06 19:42:03
【问题描述】:

我正在做一些测试,在某些情况下我有一些 Raise,例如:

@staticmethod
def concat_strings(string1, string2):
    if type(string1) is not str or type (string2) is not str:
        raise TypeError
    return string1 + string2

@staticmethod
def concat_3strings(string1, string2, string3):
    if type(string1) is not str or type(string2) is not str or type(string3) is not str:
        raise TypeError
    return string1+string2+string3

现在,如果我想检查字符串的长度是否最大为 10,那会是“属性错误”,还是应该做什么样的提升?为什么是那个?

例如:

    @staticmethod
    def concat_2strings_tam(string1, string2):
        if len(string1)>10 or len(string2)>10:
            raise AttributeError
        return string1+string2

【问题讨论】:

  • 请注意,在 Python 中不鼓励验证参数的类型,除非您正在应用类型注释。 (在这种情况下,无需在您自己的代码中显式执行此操作。)

标签: python exception exception-handling raise


【解决方案1】:

来自 python 文档:

异常值错误

当内置操作或函数接收到具有正确类型但值不适当的参数时引发,并且该情况没有由更精确的异常(例如 IndexError)描述。

听起来你想要ValueError,除非你想定义自己的自定义异常类。

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2017-07-21
    相关资源
    最近更新 更多