Which exception should I raise on bad/illegal argument combinations in Python?

Which exception should I raise on bad/illegal argument combinations in Python?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError(save must be True if recurse is True)

Theres really no point in doing class BadValueError(ValueError):pass – your custom class is identical in use to ValueError, so why not use that?

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

Which exception should I raise on bad/illegal argument combinations in Python?

I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example:

$ python -c print(sum())
Traceback (most recent call last):
File <string>, line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0

Our junior dev just found this page in a google search for python exception wrong arguments and Im surprised that the obvious (to me) answer wasnt ever suggested in the decade since this question was asked.

Leave a Reply

Your email address will not be published. Required fields are marked *