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 = messageIn 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")
try: # Some code here that might raise the custom exception except MyCustomException as e: print(e.message)
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.