RAISING CUSTOM EXCEPTIONS

In Python, you can raise custom exceptions to indicate specific error conditions in your code. Raising custom exceptions allows you to provide more meaningful error messages and better control the flow of your program when exceptional situations occur. To raise a custom exception, you need to define a new class that inherits from the Exception class or one of its subclasses.

Here's how you can create and raise a custom exception:

python
class CustomError(Exception): def __init__(self, message): self.message = message super().__init__(message) def divide_numbers(a, b): if b == 0: raise CustomError("Division by zero is not allowed.") return a / b try: result = divide_numbers(10, 0) except CustomError as e: print("An error occurred:", e)

In this example, we define a custom exception CustomError by creating a new class that inherits from the base Exception class. The constructor __init__ is used to set the error message, and we call the parent class's constructor using super().

Next, we have a function divide_numbers() that takes two numbers as input and returns the result of their division. Before performing the division, we check if the second number is zero. If it is, we raise the CustomError exception with a specific error message.

In the try-except block, we call the divide_numbers() function with 10 and 0 as arguments. Since the second number is zero, the custom exception is raised, and the except block catches it, printing the custom error message.

Custom exceptions help you communicate specific error conditions to the users of your code and make it easier to handle exceptional situations gracefully. When defining custom exceptions, consider using meaningful names and providing informative error messages to aid in debugging and understanding the cause of the error.