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

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.