What exception to throw when checking arguments?

Viewed 93

I'm defining a function in Python. It has two keyword arguments. Both can be given. If only one is given, I can find a sensible value for the other. However, it does not make sense to fill in neither of the arguments.

My implementation looks like this:

def my_fun(foo=None,bar=None):
    if foo is None:
        if bar is None:
            raise Error("My error")
        ... etc

What is the most standard error to throw? Is a ValueError the right choice?

1 Answers

The most common errors due to invalid arguments can be:

  • ValueErorr -- when values are incorrect or outside a valid range, example: passing negative numbers to a square root function -- this might be suited for your case
  • TypeError -- when parameters have the wrong type: passing string "0.2" instead of a float 0.2

Also when your both arguments are missing can be expressed in a more pythonic way as:

if foo is None and bar is None:
    raise ValueError("Expected at least one argument")

Please have a look at the builtin exceptions documentation for a wider range of exceptions and their meaning: https://docs.python.org/3/library/exceptions.html

Related