What is the appropriate exception to raise in a function to signal that a precondition was not met?
Examples:
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))
You should use both TypeError and ValueError.
The first three exceptions should be TypeErrors because we are signaling that the arguments are of an incorrect type.  From the docs:
exception
TypeErrorRaised 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.
The last exception however should be a ValueError because age is the correct type but has an incorrect value (it is negative).  From the docs:
exception
ValueErrorRaised 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With