Proper way to declare custom exceptions in modern Python?

Better Stack Team
Updated on February 3, 2023

In modern Python, the recommended way to declare custom exceptions is to create a new class that inherits from the built-in Exception class. This class should define any additional attributes or methods that are specific to the exception being created. For example:

class MyException(Exception):
    def __init__(self, message):
        self.message = message

raise MyException("This is my custom exception.")

It is also common to define custom exceptions by subclassing from the built-in Exception class or from a more specific built-in exception class such as ValueError or TypeError if it's more appropriate.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack