Search code examples
pythonexceptionerror-handling

What exception should be raised when the user calls a function with an argument that is considered an invalid choice?


Let's say I have the following code:

#!/usr/bin/env python3
from torch import Tensor
from typing import Literal


def reduce(x: Tensor, reduction: Literal["mean", "sum", "none"] = "mean") -> Tensor:
    if reduction == "mean":
        return x.mean()
    elif reduction == "sum":
        return x.sum()
    elif reduction == "none":
        return x
    else:
        raise Exception(f"Invalid choice: {reduction!r}.")

I'm just wondering what the canonical choice of built-in Python exception should be used in this scenario (in place of Exception as coded above). Is it ValueError? Or would it be something else?


Solution

  • Yes, that’s a ValueError.

    Raised when an 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.