Search code examples
pythonzen-of-python

Should I use builtin exception or define my own?


I've method or function like:

findSomething(v)

Is appropriate to raise KeyError in the case I don't find anything or it's better to define my own exception? What do you think?

I know, it isn't strictly technical question, but they said: 'Readability counts' and I need to know what others think. :)


Solution

  • If the nature of the Error is complex, and its use also repeats in other places in your code I would define a custom Error.

    Just cause it's more readable to write:

    raise MyError('reason for MyError')
    

    Than:

    raise ValueError('the is an Error of type MyError, and here is the reason...')
    

    But if it's not a repeatable part of your code, and the error is clear, I would use ValueError (before KeyError).