What is the proper way to declare custom exceptions in modern Python?


To declare a custom exception in modern Python (3.x), you need to create a new class that inherits from the built-in Exception class. Here's an example:

class MyCustomException(Exception):
    def __init__(self, message):
        self.message = message
In this example, MyCustomException is a new class that inherits from the built-in Exception class. The __init__ method allows you to provide a custom error message that can be accessed later when the exception is raised.


To raise the custom exception, use the raise keyword, followed by an instance of the exception class:

raise MyCustomException("Something went wrong")


When the custom exception is raised, it can be caught using a 'try...except' block:

try:
    # Some code here that might raise the custom exception
except MyCustomException as e:
    print(e.message)
In this example, the custom exception is caught and its error message is printed.
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.