Custom exceptions allow us to define and raise specific types of errors that are relevant to your program or application.
To create a custom exception, you can define a new class that inherits from the built-in Exception
class or any of its subclasses. You can add additional attributes or methods to your custom exception class as needed.
Let's take an example of a custom exception called InvalidInputError
:
class InvalidInputError(Exception): def __init__(self, message): self.message = message def __str__(self): return f"Invalid Input: {self.message}"
In this code, we define a custom exception class called InvalidInputError
that inherits from the Exception
class. We add an __init__
method to initialize the exception with a custom error message, and a __str__
method to provide a string representation of the exception when it is raised.
To raise the custom exception, you can use the raise
keyword followed by an instance of the custom exception class:
def divide(x, y): if y == 0: raise InvalidInputError("Cannot divide by zero") return x / y try: result = divide(10, 0) except InvalidInputError as e: print(e) # Output: Invalid Input: Cannot divide by zero
In this code, we define a function called divide
that performs division. If the divisor y
is 0
, we raise the InvalidInputError
exception with a custom error message. We catch the exception using a try-except
block and print the error message.