
Just like different built-in exceptions, Python provides us the utility to create our own user defined exceptions or custom exceptions.
In all those scenarios where you need a specific exception to suite your purpose, we can use Custom Exception in Python.
Below are the steps to create a user-defined exception or custom exception in python,
1. Create a class derived from Exception class. This class will be your solution to create a custom exception.
Suggested Tutorial: Exception Handling in Python
class GiveException(Exception):
def __init__(self, message):
self.message = message
2. This Custom Exception is to be used when a developer feels there is need to do so. This Exception can be raised using raise keyword in Python.
raise GiveException('Hello')
3. This Exception can also handled using try-except block technique for Exception Handling.
try:
// statements
except GiveException as msg:
print(msg)
Let’s consider one example where we create our own exception for a banking system,
Problem: You are the admin of a MNC. Your task is to create a custom exception that should be raised when the paid leaves of an employee is less than 2.
Plan:
Create two .py files:
exception.py -> To define our exception
employee.py -> To implement our requirement
exception.py: This file defines our custom exception class. Currently, it just get’s initialized with a message.
class LeaveException(Exception):
def __init__(self, message):
print('XXXXXXXXXXXX LEAVE EXCEPTION RAISED XXXXXXXXXXXX')
self.message = message
# other statements
employee.py: This file contains the business logic.
# let's import our exception
from exception import LeaveException
class EmployeeLeaveData:
def __init__(self, id, email, name, leaves_left):
self.id = id
self.email = email
self.name = name
self.leaves_left = leaves_left
def validate_data(self):
# raise the exception if leaves left are less than 2
if self.leaves_left < 2:
raise LeaveException(
'Leave Balance for Employee {}-{} is less than minimum threshold.'.format(self.id, self.name))
else:
print('Leaves for Employee {}-{} are more than minimum threshold.'.format(self.id, self.name))
try:
emp1 = EmployeeLeaveData(1231, '[email protected]', 'John Deol', 5)
emp1.validate_data()
emp2 = EmployeeLeaveData(1232, '[email protected]', 'Sunny Deol', 1)
emp2.validate_data()
except LeaveException as l:
print(l)
O/P
Leaves for Employee 1231-John Deol are more than minimum threshold.
XXXXXXXXXXXX LEAVE EXCEPTION RAISED XXXXXXXXXXXX
Leave Balance for Employee 1232-Sunny Deol is less than minimum threshold.
So, now we have created our own custom exception for our own purpose. Hope it was helpful tutorial for you.
NEXT TUTORIAL >> File Handling in Python
