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. For example:

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

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

Watch a course Python - The Practical Guide

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

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.

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.

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.