I have a situation where a user may provide bad data to get to a datapoint that may not exist. Currently, the error types raised when these problems happen is not clear or straightforward.
In my API, I intend to create a error to catch in the UI (or I'll let the UI framework handle it by reporting it straight to the user, which I've tested and know works.):
class DataError(ValueError):
'''
raise this error with a message of what was wrong,
will also be caught when catching general ValueErrors
or other Exceptions that ValueError subclasses
'''
And usage:
if user_input not in accepted_values:
raise DataError('bad user_input: {0}'.format(user_input))
I do get rather opinionated about my approach, and I want rather unassailable code. I'm aware of the upsides, as I can catch this specific exception without hiding others. But I can't think of any downsides.
What are the downsides of doing this as opposed to just raising my error message with ValueError
?
Writing custom exceptions is almost always the right thing to do. With that said, there are a few minor potential downsides to subclassing an exception:
Does your error correspond exactly to an error in the standard library? For example, implementing an object that looks like a dict, you just want to throw KeyError
.
Are you subclassing the right thing? In your example, anyone catching ValueError
will also catch DataError
. Depending on your use case, there may be times where this isn't appropriate.
Does the exception you are subclassing provide additional functionality? It's a class, it may have all sorts of methods. If you subclass an exception, you ought to verify that all its methods make sense for your error situation.
In other circumstances, an exception may not be appropriate at all. Is there an 'no value' result (e.g. None
or []
) that would be more suitable?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With