» Subscribe to the dbader.org YouTube Channel for more videos.
Let’s say we want to validate an input string representing a person’s name in our application. A simple toy example might look like this:
def validate(name): if len(name) < 10: raise ValueError
If the validation fails it throws a
ValueError. That feels kind of Pythonic already… We’re doing great!
However, there’s one downside to this piece of code: Imagine one of our team mates calls this function as part of a library and doesn’t know much about its internals.
When a name fails to validate it’ll look like this in the debug stacktrace:
>>> validate('joe') Traceback (most recent call last): File "<input>", line 1, in <module> validate('joe') File "<input>", line 3, in validate raise ValueError ValueError
This stacktrace isn’t really all that helpful. Sure, we know that something went wrong and that the problem has to do with an “incorrect value” of sorts.
But to be able to fix the problem our team mate almost certainly has to look up the implementation of
validate(). But reading code costs time. And it adds up quickly…
Luckily we can do better! Let’s introduce a custom exception type for when a name fails validation. We’ll base our new exception class on Python’s built-in
ValueError, but make it more explicit by giving it a different name:
class NameTooShortError(ValueError): pass def validate(name): if len(name) < 10: raise NameTooShortError(name)
See how we’re passing
name to the constructor of our custom exception class when we instantiate it inside
validate? The updated code results in a much nicer stacktrace for our team mate:
>>> validate('jane') Traceback (most recent call last): File "<input>", line 1, in <module> validate('jane') File "<input>", line 3, in validate raise NameTooShortError(name) NameTooShortError: jane
Now, imagine you are the team mate we were talking about… Even if you’re working on a code base by yourself, custom exception classes will make it easier to understand what’s going on when things go wrong. A few weeks or months down the road you’ll have a much easier time maintaining your code. I’ll vouch for that 😃
P.S. If you enjoyed this screencast and you’d like to see more just like it then subscribe to my » YouTube channel with free screencasts and video tutorials for Python developers «