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

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

Asked on November 4, 2018 in Python.
Add Comment


  • 3 Answer(s)

    I would objective raise ValueError, except you want 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")
    

    There is actually no point in doing class BadValueError(ValueError):pass – your tradition class is matching in use to ValueError, so why not use that in python?

    Answered on November 4, 2018.
    Add Comment

    Just inherit from ValueError:

    class IllegalArgumentError(ValueError):
        pass
    

    It is typically higher to form your own exceptions, however inherit from a intrinsic one, that is as about to what you would like as doable.
    If you would like to catch that specific error, it’s useful to possess a reputation.

    Answered on November 4, 2018.
    Add Comment

    I’ve principally simply seen the builtin ValueError utilized in this example.

     

    Answered on November 4, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.