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.