python - 未满足前提条件的正确异常(exception)是什么?

标签 python exception conditional-statements

在函数中引发什么异常以表示不满足先决条件?

例子:

def print_stats(name, age):
    if name is None:
        raise Exception("name cannot be None")
    if not type(name) is str:
        raise Exception("name must be a string")

    if age is None:
        raise Exception("age cannot be None")
    if age < 0:
        raise Exception("age cannot be negative")

    print("{0} is {1} years old".format(name, age))

最佳答案

您应该同时使用 TypeErrorValueError

前三个异常应该是TypeError,因为我们表示参数的类型不正确。来自docs :

exception TypeError

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

然而,最后一个异常应该是 ValueError,因为 age 是正确的类型但具有不正确的值(它是负数)。来自docs :

exception ValueError

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

关于python - 未满足前提条件的正确异常(exception)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26915737/

相关文章:

PostgreSQL:如何捕获函数中的异常?

python - 我怎样才能既注册蓝图又将该应用程序添加到 flask 管理员

python - 如何为可迭代的字典对象实现 "next"?

exception - 寻找描述通过异常进行尾递归优化的引用资料

java - Rhino 中的 JS 属性赋值抛出异常有意义吗?

excel - 如何将条件添加到显示部分或操作的源数据的数据透视表

javascript - while(true)条件有什么意义?

r Shiny 的条件显示

python - NumPy相关函数中索引的范围

python - 根据 Keras 损失示例记录每个批处理的 Keras 指标