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")
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)
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.