Skip to main content
 首页 » 编程设计

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

2025年05月04日13artech

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

例子:

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)) 

请您参考如下方法:

您应该同时使用 TypeError 和 ValueError。

前三个异常应该是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.