User Defined Exception in Python
A user defined exception in Python is an exception that is constructed by the user or programmer to represent a specific error condition or exceptional situation in a program. It is also known as a custom exception.
Python offers a wide range of standard built-in exceptions to handle common errors. Sometimes, there may be situations where built-in exceptions are not sufficient to handle the different exceptions that occur in the application program.
In this situation, users may need to define their own custom exceptions to handle specific errors or to add more context to error handling.
For example, if the user wants to withdraw greater than its balance from the ATM machine, it leads to the exception. Any standard inbuilt exception cannot handle such a kind of exception.
In this case, the user can define its own custom exception that will occur when someone will want to attempt to withdraw the amount greater than its balance. The exception handler in this case may display a customize message that you cannot withdraw money greater than the account balance.
Another popular example of a user-defined exception scenario involves a situation of social media platform where a user tries to create a password that doesn’t meet the required criteria.
Let’s say the social media platform like Facebook mandates that passwords must contain at least eight characters, including at least one uppercase letter, one lowercase letter, one digit, and one special character.
If a user tries to set a password that doesn’t meet these criteria, the system can raise a custom exception named InvalidPasswordException. This exception could notify the user about the specific password requirements haven’t been met.
How to Create User Defined Exception in Python?
User-defined exceptions help to define their own customize message, which we can display whenever any exception raises. We know that every exception is a class in Python and Exception class is a base class of all the exceptions. It means that whether built-in or user-defined exceptions, all are always derived from the Exception base class.
To create a user defined exception, first, we need to create a new exception class which is inherited from the Exception base class.
Syntax for Defining a Custom Exception Class
The general syntax to create a user defined exception class is as follows:
class user_defined_exception(Exception):
# Constructor
def __init__(self, args)
self.args = args
# Additional methods and attributes can be added hereIn the above syntax, user_defined_exception is the name of exception class created by the user. This exception class is derived from the Exception base class.
This class may have a constructor that may take argument passed to it and may also include a group of statements that will execute when it is called during object creation. The argument may be passed to the created exception when the exception occurs.
After creating a user defined exception class, we will have to raise the created user defined exception on the occurrence of certain events. We generally raise an exception according to the possibility of the occurrence of a certain event. The general syntax to raise an exception in Python is as follows:
raise user_defined_exception(message)
This statement raises the user_defined_exception on the occurrence of a certain event. The argument message typically contains information about the exception, like an error message or additional details that we pass to the constructor of the class to be displayed when certain conditions occur in the program.
At last, we write a set of statements inside the try block that can create an exception in the program. The except block catches and handles the user_defined_exception.
Simple User Defined Exception Examples in Python
The below example code shows examples of user defined exception.
Example 1:
# Create a user defined exception class that inherits from Exception class.
class MyException(Exception):
pass
try:
raise MyException("My exception")
# Exception value stored in m.
except MyException as m:
print(m)
Output:
My exception
In this example, we have defined a custom exception class named MyException. Inside the try block, we have raised an instance of MyException with the message “My exception”. The except block caught the raised MyException and assigned it to the variable m.
Finally, we have displayed the message contained within the MyException instance, which is “My exception”. This code demonstrates the creation of a custom exception class and how to handle instances of that exception using a try-except block, access and display the exception message when caught.
Example 2:
# Create a user defined exception class that inherits from RuntimeError class.
class MyException(RuntimeError):
pass
try:
raise MyException("It is a user-defined exception.")
# Exception value stored in m.
except MyException as m:
print(m)
Output:
It is a user-defined exception.
In this example, we have used RuntimError exception class in the place of Exception class. The RuntimeError in Python is a built-in exception class that is a subclass of Exception class. It is typically raised when an error occurs that doesn’t specifically match any other predefined or built-in exception.
Advanced User Defined Exception Examples
Example 3:
class PasswordLengthError(Exception):
def __init__(self, password_length):
self.password_length = password_length
self.message = "Password length should be at least 8 characters. Current length: " + str(password_length)
def validate_password(password):
if len(password) < 8:
raise PasswordLengthError(len(password))
else:
print("Password meets the length criteria")
try:
user_password = input("Enter your password: ")
validate_password(user_password)
except PasswordLengthError as e:
print(e.message)
Output:
First run:
Enter your password: Tripti12345
Password meets the length criteria
Second run:
Enter your password: Deepak
Password length should be at least 8 characters. Current length: 6
In this example, we have created a user defined exception named PasswordLengthError that inherits from Exception base class. This class contains a constructor __init__() that initializes instance variable such as password_length that caused the exception. The message attribute stores the error message, concatenating strings and converting password_length to a string using str().
Then, we have defined a validate_password() function that checks if the provided password meets a certain length criteria (at least 8 characters). If the password length is less than 8 characters, it raises a PasswordLengthError exception with a message containing the current password length.
Inside the try block, we have taken the password as an input from the user and stored it into a variable named user_password. After that, we have called the function by passing the value stored in the variable. The try-except block captures the raised PasswordLengthError. If the exception occurs (e.g., when the password length is insufficient), it displays the custom error message associated with the PasswordLengthError.
Example 4:
class InsufficientBalance(Exception):
def __init__(self, message = "You cannot withdraw more than the available balance"):
self.message = message
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalance()
else:
self.balance -= amount
print("Withdrawal successful")
print("Remaining balance: ", self.balance)
# Assuming an initial balance of $200
account = BankAccount(200) # Object creation
try:
withdrawal_amount = 250 # Attempting to withdraw more than the balance
account.withdraw(withdrawal_amount)
except InsufficientBalance as e:
print(e.message) # Displaying the custom message for insufficient balance
Output:
You cannot withdraw more than the available balance
The above program code raises an exception if the withdrawal amount entered is greater than the available balance amount. If the entered amount is less than the available balance, the program updates the balance. If greater, it raises an exception that displays the error message like “You cannot withdraw more than the available balance”.
Handle to Multiple Custom Exceptions in Python
Python allows the creation of multiple custom exceptions based on different use cases. Here is an example code of handling multiple user-defined exceptions in Python:
Example 5:
class CustomException1(Exception):
pass
class CustomException2(Exception):
pass
try:
choice = int(input("Enter 1 or 2: "))
if choice == 1:
raise CustomException1("Custom Exception 1 raised")
elif choice == 2:
raise CustomException2("Custom Exception 2 raised")
else:
print("Invalid choice")
except CustomException1 as e1:
print("Caught Custom Exception 1:", e1)
except CustomException2 as e2:
print("Caught Custom Exception 2:", e2)
Output:
Enter 1 or 2: 1
Caught Custom Exception 1: Custom Exception 1 raised
In this example, we have defined two custom exception classes, CustomException1 and CustomException2. Inside the try block, user input (choice) determines which custom exception to raise (CustomException1 or CustomException2) based on the input value.
If the input value is 1, it raises CustomException1; if it’s 2, it raises CustomException2. The except blocks are used to catch and handle these specific custom exceptions separately:
- except CustomException1 as e1 catches CustomException1 and displays a message along with the exception details (e1).
- except CustomException2 as e2 catches CustomException2 and displays a message along with the exception details (e2).
Example 6:
class MyError(Exception):
# Base class for other custom exceptions
pass
class SmallAgeError(MyError):
# Raised this exception when age is smaller than 0
pass
class LargeAgeError(MyError):
# Raised this exception when age is greater than 99
pass
# Outside class definition
age = -5 # For example purposes
try:
if age < 0: raise SmallAgeError("Age should be greater than 0") elif age > 99:
raise LargeAgeError("Age should be smaller than 99")
else:
print("Age is:", age)
except SmallAgeError as s:
print(s)
except LargeAgeError as l:
print(l)
Output:
Age should be greater than 0
In this example, we have three custom exception classes (MyError, SmallAgeError, LargeAgeError), where SmallAgeError is raised for ages smaller than 0, and LargeAgeError is raised for ages greater than 99. The try block checks the value of age and raises the appropriate custom exception based on its value.
Inside the except blocks:
- except SmallAgeError as s catches and handles SmallAgeError exception and displays the corresponding error message.
- except LargeAgeError as l catches and handles LargeAgeError exception, and displays the associated error message.
In this tutorial, we have explained custom exception or user defined exception in Python with the help of various example programs. Hope that you will have understood the concept of creating multiple user-defined exceptions. Stay tuned with the next tutorial where we will learn how to raise an exception in Python.
Thanks for reading!!!






