Define Custom Exceptions in Python
Last Updated :
03 Jun, 2024
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:
Python
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.
Why Define Custom Exceptions?
Custom exceptions are useful in the following scenarios:
- Clarity: They provide clear, specific error messages that are relevant to your application.
- Granularity: They allow for more fine-grained error handling, making it easier to pinpoint and address specific issues.
- Reusability: They can be reused across different parts of your application or even in different projects.
1. 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:
Python
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.
2. Defining a Custom Exception
To define a custom exception we create a new class that inherits from the built-in ‘Exception’ class and override its methods to customize its behavior for specificity.
Python
class MyCustomError(Exception):
"""Exception raised for custom error in the application."""
def __init__(self, message, error_code):
super().__init__(message)
self.error_code = error_code
def __str__(self):
return f"{self.message} (Error Code: {self.error_code})"
3. Raising a Custom Exception
To raise a custom exception, use the raise keyword followed by an instance of your custom exception.
Python
def divide(a, b):
if b == 0:
raise MyCustomError("Division by zero is not allowed", 400)
return a / b
Here the divide method raises the ‘MyCustomError’ when an attempt to divide by zero is made.
4. Handling Custom Exceptions
Custom exceptions can be handled similar to built-in exceptions using a `try…except` block.
Python
try:
result = divide(10, 0)
except MyCustomError as e:
print(f"Caught an error: {e}")
Here divide function raises `MyCustomError` and it is caught and handled by the `except` block. Additional attributes and methods can be used to enhance Custom Exceptions to provide more context or functionality.
Python
class FileProcessingError(Exception):
def __init__(self, message, filename, lineno):
super().__init__(message)
self.filename = filename
self.lineno = lineno
def __str__(self):
return f"{self.message} in {self.filename} at line {self.lineno}"
try:
raise FileProcessingError("Syntax error", "example.txt", 13)
except FileProcessingError as e:
print(f"Caught an error: {e}")
Tips for Effective Use of Custom Exceptions
When defining and using custom exceptions, consider the following tips to ensure they are effective and maintainable:
- Naming: Use clear and descriptive names that end with Error to indicate that they are exceptions.
- Documentation: Provide docstrings for your custom exceptions to explain when they should be used.
- Hierarchy: Create a hierarchy of exceptions if your application requires handling different types of errors differently python
Please Login to comment...