Python User-defined Exception

‮.www‬theitroad.com

In Python, you can create your own custom exceptions by creating a new class that inherits from the built-in Exception class.

Here's an example of how to define a custom exception in Python:

class MyException(Exception):
    pass

In this example, we've defined a new class called MyException that inherits from the Exception class. This class doesn't contain any additional methods or attributes, but you can add your own as needed.

Once you've defined your custom exception, you can raise it using the raise statement:

raise MyException("An error occurred")

In this example, we've raised a new instance of the MyException class with the message "An error occurred".

You can also catch your custom exception using the same try and except blocks that you would use for built-in exceptions:

try:
    raise MyException("An error occurred")
except MyException as e:
    print("Caught an instance of MyException:", e)

In this example, we've raised a new instance of the MyException class and caught it using an except block that specifies the MyException class. The program will print "Caught an instance of MyException: An error occurred" to the console.

Custom exceptions can be useful for adding more descriptive error messages, creating new types of errors, or organizing error handling in more meaningful ways. By creating your own exceptions, you can add more flexibility and control to your Python programs.