Dan Bader

Make your Python code more readable with custom exception classes

In this short screencast I’ll walk you through a simple code example that demonstrates how you can use custom exception classes in your Python code to make it easier to understand, easier to debug, and more maintainable.

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>
  File "<input>", line 3, in validate
    raise 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):

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>
  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 «

📘 Python Tricks: The Book — A Buffet of Awesome Python Features: My new book that teaches you the coolest aspects of Python with short and easy to digest examples. » Click here to get a free sample chapter

Improve Your Python with a fresh 🐍 Python Trick 💌 every couple of days

🔒 No spam ever. Unsubscribe any time.

This article was filed under: oop, programming, python, and video.

Related Articles:
Latest Articles:
  • Context Managers and the “with” Statement in Python – The “with” statement in Python is regarded as an obscure feature by some. But when you peek behind the scenes of the underlying Context Manager protocol you’ll see there’s little “magic” involved.
  • Installing Python and Pip on Windows – In this tutorial you’ll learn how to set up Python and the Pip package manager on Windows 10, completely from scratch.
  • Sublime Text Settings for Writing Clean Python – How to write beautiful and clean Python by tweaking your Sublime Text settings so that they make it easier to adhere to the PEP 8 style guide recommendations.
  • How Sublime Text’s Preferences Work – Sublime Text uses a powerful text-based settings system that can be a little intimidating when you encounter it for the first time. This article gives an overview of the system and points out some common mistakes to avoid.
  • Writing Clean Python With Namedtuples – Python comes with a specialized “namedtuple” container type that doesn’t seem to get the attention it deserves. It’s one of these amazing features in Python that’s hidden in plain sight.
  • Lambda Functions in Python: What Are They Good For? – An introduction to “lambda” expressions in Python: What they’re good for, when you should use them, and when it’s best to avoid them.
← Browse All Articles