Defining a Custom Exception
To define a custom exception in Python, you need to create a new class that inherits from the built-in Exception
class or one of its subclasses. Here’s a basic example:
class MyCustomError(Exception):
"""Exception raised for custom error scenarios.
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
self.message = message
super().__init__(self.message)
In this example, MyCustomError
is a custom exception class that inherits from Exception
. It has an __init__
method that takes a message
parameter and passes it to the base class constructor.
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the program’s instructions. When an error occurs, Python raises an exception, which can be caught and handled using try
and except
blocks. Here’s a simple example of handling a built-in exception:
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
In this example, ZeroDivisionError
is a built-in exception that gets raised when you attempt to divide by zero.
Contact Us