Should I use builtin exception or define my own?

88 views Asked by At

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. :)

3

There are 3 answers

1
ShaharA On BEST ANSWER

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).

0
Andrew_Lvov On

Might be closed as opinion-based, but.

I prefer to limit KeyError, ValueError etc to local scope, i.e no bigger than inside 1 function, preferably logical block inside.

Let's say you've caught a KeyError a couple layers from the original place the exception has taken place. It gives you basically no information and could have happened basically anywhere. A function calling another one shouldn't know about implementation details of the callee. Also you're not writing a code to check exception stack trace and use it in your code logic, are you ?

Defining custom exception gives you the opportunity to describe location and high-level explanation of an issue like UserNotFound or NoMatchingChannel. The code where you will catch it will give more insight about what is the issue and how to deal with it.

0
Aida On

Well, I guess readability is more related to how you code, say how you name variables, functions, etc., how you structure your code and comment it.

But, regarding the exception handling question that you have: these are the things I think you should consider:

1- If the function gets a valid input and does not find anything you shouldn't throw or define an exception. You just need to return a value that represents you didn't find anything and/or just print a proper message.

2- If the input parameter, v, is invalid depending whether it is an object instantiated from a class or just a primitive type, you could define a proper exception for it or just catch a built-in exception, respectively.