- Learning Objectives
- Prerequisites
- Introduction
- What are User-Defined Exceptions?
- Why are User-Defined Exceptions Required?
- Creating a Custom Exception
- Inheriting from the Exception Class
- Raising User-Defined Exceptions
- Handling User-Defined Exceptions
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand User-Defined Exceptions.
- Create custom exception classes.
- Inherit from the built-in Exception class.
- Raise and handle custom exceptions.
- Use custom exceptions in real-world applications.
- Write cleaner and more maintainable programs.
Before learning this chapter, you should know:
- Exception Handling
- try-except Blocks
- else and finally Blocks
- raise Keyword
- Classes and Inheritance
Python provides many built-in exceptions such as:
- ValueError
- TypeError
- IndexError
- KeyError
These exceptions are suitable for common programming errors.
However,
real-world applications often have their own business rules.
For example,
a Banking Application may need to display
Insufficient Balance
instead of
ValueError
Similarly,
a College Management System may require
Invalid Student ID
instead of a generic exception.
To handle such situations,
Python allows developers to create their own exceptions.
These are called User-Defined Exceptions or Custom Exceptions.
A User-Defined Exception is a custom exception created by the programmer to represent application-specific errors.
It is created by defining a class that inherits from Python's built-in
Exceptionclass.
A User-Defined Exception is a custom exception created to handle business-specific or application-specific errors.
Suppose we are developing an ATM Application.
If the account balance is
₹5,000
and the customer requests
₹10,000
Using
ValueErroris technically correct,
but it does not clearly describe the business problem.
Instead,
we can create
InsufficientBalanceError
which clearly communicates the reason for the failure.
This makes the application easier to understand and maintain.
User-Defined Exceptions are commonly used in:
- Banking Applications
- Hospital Management Systems
- Student Management Systems
- E-Commerce Websites
- Airline Reservation Systems
- Inventory Management
- Payment Gateways
- REST APIs
A custom exception is created by inheriting from
ExceptionSyntax
class CustomException(Exception):
passExample
class InvalidAgeError(Exception):
passEvery custom exception should inherit from
ExceptionExample
class InsufficientBalanceError(Exception):
passThis allows Python's exception handling mechanism to recognize the custom exception.
A custom exception is raised using the
raisekeyword.
Example
raise InvalidAgeError("Age must be at least 18.")A custom exception is handled just like any built-in exception.
Example
try:
raise InvalidAgeError("Age must be at least 18.")
except InvalidAgeError as error:
print(error)When a custom exception is raised,
Python searches for the nearest matching
exceptblock.
If found,
the exception is handled.
Otherwise,
the program terminates and displays a traceback.
Program Starts
↓
Business Rule Checked
↓
Rule Violated?
↓
No
↓
Continue Program
------------------------
Yes
↓
Create Custom Exception Object
↓
raise Statement
↓
Search Matching except Block
↓
Found?
↓
Yes
↓
Handle Exception
↓
Continue Program
------------------------
No
↓
Program Terminates
- Creates meaningful error types.
- Improves code readability.
- Simplifies debugging.
- Represents business rules clearly.
- Produces maintainable applications.
- Give custom exceptions meaningful names.
- End exception class names with "Error".
- Inherit from
Exception. - Provide clear error messages.
- Use custom exceptions only for business-specific problems.
Not inheriting from
ExceptionCustom exceptions should always inherit from Exception (or one of its subclasses).
Using generic names.
❌ Bad
class MyException(Exception):✅ Better
class InvalidAgeError(Exception):Using custom exceptions for ordinary programming mistakes.
Reserve custom exceptions for business rules and domain-specific errors.
A User-Defined Exception is a custom exception created by the programmer for application-specific errors.
By creating a class that inherits from Exception.
So that Python recognizes them as exceptions and they work correctly with try-except.
Using the raise keyword.
Yes.
They can include custom messages just like built-in exceptions.
- User-Defined Exceptions are custom exceptions.
- Inherit from
Exception. - Raise using
raise. - Handle using
try-except. - Use for business-specific validation.
In this chapter, we learned:
- User-Defined Exceptions
- Creating Custom Exception Classes
- Inheriting from
Exception - Raising Custom Exceptions
- Handling Custom Exceptions
- Internal Working
- Best Practices
- Common Mistakes
- Interview Questions
- Quick Revision
Write a Python program to create and raise a custom exception.
class InvalidAgeError(Exception):
pass
raise InvalidAgeError("Age must be at least 18.")InvalidAgeError: Age must be at least 18.
A custom exception named
InvalidAgeErroris created by inheriting from
ExceptionThe exception is raised using the
raisestatement.
class InvalidAgeError(Exception):
pass
try:
age = int(input("Enter Age : "))
if age < 18:
raise InvalidAgeError("Age must be at least 18.")
print("Eligible")
except InvalidAgeError as error:
print(error)Enter Age : 16
Age must be at least 18.
The custom exception is raised when the condition fails
and handled using
except InvalidAgeErrorclass InsufficientBalanceError(Exception):
pass
balance = 5000
withdraw = int(input("Enter Amount : "))
if withdraw > balance:
raise InsufficientBalanceError("Insufficient Balance.")
balance -= withdraw
print("Remaining Balance :", balance)Enter Amount : 7000
InsufficientBalanceError: Insufficient Balance.
Instead of raising a generic
ValueErrorthe program raises a business-specific exception.
class InvalidMarksError(Exception):
pass
marks = int(input("Enter Marks : "))
if marks < 0 or marks > 100:
raise InvalidMarksError("Marks must be between 0 and 100.")
print("Marks Accepted")Enter Marks : 120
InvalidMarksError: Marks must be between 0 and 100.
class InvalidSalaryError(Exception):
pass
salary = int(input("Enter Salary : "))
if salary < 0:
raise InvalidSalaryError("Salary cannot be negative.")
print("Salary Accepted")Enter Salary : -5000
InvalidSalaryError: Salary cannot be negative.
class WeakPasswordError(Exception):
pass
password = input("Enter Password : ")
if len(password) < 8:
raise WeakPasswordError(
"Password must contain at least 8 characters."
)
print("Password Accepted")Enter Password : admin
WeakPasswordError: Password must contain at least 8 characters.
The custom exception clearly indicates the business rule.
class AdmissionError(Exception):
pass
percentage = float(input("Enter Percentage : "))
if percentage < 60:
raise AdmissionError(
"Minimum 60% is required for admission."
)
print("Admission Approved")Enter Percentage : 52
AdmissionError: Minimum 60% is required for admission.
class OutOfStockError(Exception):
pass
stock = 5
required = int(input("Required Quantity : "))
if required > stock:
raise OutOfStockError("Product is out of stock.")
print("Order Confirmed")Required Quantity : 10
OutOfStockError: Product is out of stock.
class BookNotAvailableError(Exception):
pass
available = False
if not available:
raise BookNotAvailableError(
"Requested book is not available."
)
print("Book Issued")BookNotAvailableError:
Requested book is not available.
class InvalidAgeError(Exception):
pass
try:
age = int(input("Enter Age : "))
if age < 18:
raise InvalidAgeError(
"Age must be at least 18."
)
print("Registration Successful")
except InvalidAgeError as error:
print(error)Enter Age : 15
Age must be at least 18.
The exception is
- Created
- Raised
- Handled
using Python's exception handling mechanism.
Program Starts
↓
Input Accepted
↓
Business Rule Checked
↓
Rule Violated?
↓
No
↓
Continue Program
------------------------
Yes
↓
raise
↓
Custom Exception Object Created
↓
Matching except Found
↓
Handle Exception
↓
Program Continues
Program
↓
Input
↓
Business Validation
↓
Condition Failed
↓
Custom Exception Object
↓
raise
↓
except Block
↓
Program Continues
- Represents business rules clearly.
- Improves readability.
- Produces meaningful error messages.
- Simplifies debugging.
- Makes enterprise applications easier to maintain.
- Inherit custom exceptions from
Exception. - Use descriptive class names ending with
Error. - Provide meaningful exception messages.
- Raise exceptions only for exceptional conditions.
- Handle exceptions appropriately.
Creating a custom exception without inheriting from Exception.
❌ Incorrect
class InvalidAgeError:
passUsing unclear exception names.
❌ Incorrect
class MyError(Exception):✅ Better
class InvalidAgeError(Exception):Using custom exceptions for syntax or programming mistakes.
Custom exceptions should represent application-specific rules.
Raising custom exceptions without meaningful messages.
Always explain why the exception occurred.
A User-Defined Exception is a custom exception created by the programmer for application-specific or business-specific errors.
ExceptionTo represent business rules clearly and improve code readability.
Using the raise keyword.
Yes.
They can contain meaningful messages just like built-in exceptions.
Using try-except, just like built-in exceptions.
When built-in exceptions do not clearly describe an application's business rules.
- Create an
InvalidAgeError. - Create an
InsufficientBalanceError. - Create a
WeakPasswordError. - Create an
InvalidMarksError. - Create a
BookNotAvailableError.
- Custom Exception → Programmer-created exception.
- Inherit from
Exception. - Raise using
raise. - Handle using
try-except. - Use meaningful class names and messages.
In this chapter, we learned:
- User-Defined Exceptions
- Creating Custom Exception Classes
- Raising Custom Exceptions
- Handling Custom Exceptions
- Business Rule Validation
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision