Search code examples
pythonpython-3.xexceptionerror-handlingcustomization

Which is better using custom exceptions or using ValueError


For both developers and users ??? which one is better ? defining a new custom error like this :

def Passed_Empty_Text(Exception):
    def __str__(self):
        return 'Empty String Passed'
raise Passed_Empty String
# And More Exceptions

or using :

 raise ValueError('Passed Empty String')

which one is better ??


Solution

  • Both :)

    Inherit from ValueError and give your exception a meaningful name.

    class EmptyError(ValueError):
        ...
    

    Now you have a more specific ValueError when you need it. Whether this actually increases the user/developer-friendliness depends on personal taste and the larger context.