W3docs

Proper way to declare custom exceptions in modern Python?

To declare a custom exception in Python, you can create a new class that inherits from the built-in Exception class.

To declare a custom exception in Python, you can create a new class that inherits from the built-in Exception class. For example:

Declare custom exceptions in modern Python

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

try:
    raise MyCustomException("An error occurred")
except Exception as e:
    print(e)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Alternatively, you can also use the raise statement with a built-in exception class, like ValueError or TypeError.

Raise a built-in exception in Python

try:
    raise ValueError("An error occurred")
except Exception as e:
    print(e)

In both cases, you can include a custom error message as a string argument to the exception class. This message can be accessed from the exception object when the exception is caught, and can be used to display a more informative error message to the user.

Print any custom exception's message in Python

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

try:
    raise MyCustomException("An error occurred")
except MyCustomException as e:
    print(e.message)

It is also a good idea to include a docstring in your custom exception class to provide a clear description of when the exception should be raised and what it means.

Documenting a Python exception by commenting

class MyCustomException(Exception):
    """Exception raised when a specific error condition occurs.

    Attributes:
        message -- explanation of the error
    """
    def __init__(self, message):
        self.message = message

By following these guidelines, you can effectively declare and use custom exceptions in your Python code.