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.
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})"
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