Custom Exceptions in Python
Learn how to create your own exception classes in Python for application-specific errors.
What are Custom Exceptions?
Python provides many built-in exceptions such as
ValueError, TypeError and
ZeroDivisionError.
Sometimes an application needs an error type that is specific to its own business rules or requirements. In that situation, we can create a custom exception.
Custom Exception Flow
Create Exception Class
Create a new class derived from the Exception class.
Raise Exception
Use raise when the required condition occurs.
Handle Exception
Handle the custom exception using except.
Basic Syntax
class MyException(Exception):
pass
A custom exception class normally inherits from
the built-in Exception class.
Simple Example
class AgeError(Exception):
pass
try:
age = 15
if age < 18:
raise AgeError("Age must be 18 or above")
except AgeError as error:
print(error)
Output:
Age must be 18 or above
Here, AgeError is a custom exception
created by the programmer.
Custom Exception with User Input
class AgeError(Exception):
pass
try:
age = int(
input("Enter your age: ")
)
if age < 18:
raise AgeError("You must be 18 or above")
print("Valid age")
except AgeError as error:
print("Error:", error)
Example Output:
Enter your age: 16
Error: You must be 18 or above
Example: Marks Validation
class InvalidMarksError(Exception):
pass
try:
marks = int(
input("Enter marks: ")
)
if marks < 0 or marks > 100:
raise InvalidMarksError(
"Marks must be between 0 and 100"
)
print("Valid marks:", marks)
except InvalidMarksError as error:
print("Error:", error)
Example Output:
Enter marks: 120
Error: Marks must be between 0 and 100
Custom Exception with a Value
A custom exception can also store information about the error.
class SalaryError(Exception):
def __init__(self, salary):
self.salary = salary
try:
salary = 5000
if salary < 10000:
raise SalaryError(salary)
except SalaryError as error:
print("Invalid salary:", error.salary)
Output:
Invalid salary: 5000
Multiple Custom Exceptions
A program can contain more than one custom exception class for different business rules.
class AgeError(Exception):
pass
class MarksError(Exception):
pass
try:
age = 16
marks = 120
if age < 18:
raise AgeError("Age must be 18 or above")
if marks < 0 or marks > 100:
raise MarksError("Invalid marks")
except AgeError as error:
print(error)
except MarksError as error:
print(error)
Each custom exception can have its own handler.
Custom Exception with Function
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(
"Insufficient balance"
)
return balance - amount
try:
balance = 5000
amount = 7000
remaining = withdraw(balance, amount)
print("Remaining balance:", remaining)
except InsufficientBalanceError as error:
print("Error:", error)
Output:
Error: Insufficient balance
Practical Uses of Custom Exceptions
Validation
Used for application-specific validation errors.
Business Rules
Used when a business rule is not satisfied.
Application Errors
Used to describe specific application problems.
Built-in vs Custom Exceptions
Built-in Exception:
Already provided by Python, such as
ValueError and TypeError.
Custom Exception: Created by the programmer for a specific application requirement.
Best Practices
Meaningful Names
Give the custom exception a clear and meaningful name.
Useful Messages
Provide a clear message that explains the problem.
Specific Purpose
Create custom exceptions only when a specific application requirement needs them.
Common Mistakes
- Creating unnecessary custom exceptions.
- Using unclear exception names.
- Not providing a meaningful error message.
-
Forgetting to inherit from the
Exceptionclass.
Practice Programs
- Create a custom exception for invalid age.
- Create a custom exception for invalid marks.
- Create a custom exception for insufficient balance.
- Create two custom exceptions for two different application rules.
- Use a custom exception inside a function.
Summary
Custom exceptions are user-defined exceptions created
for application-specific requirements. They normally
inherit from the built-in Exception class.
Custom exceptions can be raised using
raise and handled using
try and except. They are useful
for validation, business rules and application-specific
errors.