Python Training by 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.

» Subscribe to the dbader.org YouTube Channel for more Python tutorials.

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 teammates 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 teammate 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 teammate:

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

<strong><em>Improve Your Python</em></strong> with a fresh 🐍 <strong>Python Trick</strong> 💌 every couple of days

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:
  • Using get() to return a default value from a Python dict – Python’s dictionaries have a “get” method to look up a key while providing a fallback value. This short screencast tutorial gives you a real-world example where this might come in handy.
  • Comprehending Python’s Comprehensions – One of my favorite features in Python are list comprehensions. They can seem a bit arcane at first but when you break them down they are actually a very simple construct.
  • 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.
  • Abstract Base Classes in Python – Abstract Base Classes (ABCs) ensure that derived classes implement particular methods from the base class. In this tutorial you’ll learn about the benefits of abstract base classes and how to define them with Python’s built-in abc module.
  • 6 things you’re missing out on by never using classes in your Python code – Maybe you’ve been using Python for a while now and you’re starting to feel like you’re getting the hang of it. But one day you catch yourself thinking: “What about classes?”
Latest Articles:
← Browse All Articles