Custom exceptions allow you to create your own error types.
They are useful when built-in exceptions do not clearly describe your program’s specific error.
Custom exceptions make your code more readable, professional, and organized.
WHY CREATE CUSTOM EXCEPTIONS?
• Enforce business rules
• Improve error clarity
• Make debugging easier
• Handle application-specific problems
CREATING A CUSTOM EXCEPTION
To create a custom exception, define a class that inherits from Exception.
class CustomError(Exception):
pass
Now you can use this exception in your program.
SIMPLE EXAMPLE
class InvalidAgeError(Exception):
passage = int(input("Enter your age: "))if age < 0:
raise InvalidAgeError("Age cannot be negative.")print("Age accepted.")
If the user enters a negative age, the custom exception will be raised.
USING CUSTOM EXCEPTION WITH TRY-EXCEPT
class InvalidMarksError(Exception):
passtry:
marks = int(input("Enter marks: "))
if marks < 0 or marks > 100:
raise InvalidMarksError("Marks must be between 0 and 100.")
except InvalidMarksError as e:
print("Error:", e)
Here, the custom exception is raised and handled properly.
ADDING CUSTOM MESSAGE WITH INIT
You can customize the exception class further.
class NegativeNumberError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)try:
num = int(input("Enter number: "))
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
except NegativeNumberError as e:
print("Error:", e)
REAL-WORLD USE CASE
Example: Bank account balance validation
class InsufficientBalanceError(Exception):
passbalance = 500
withdraw = 1000if withdraw > balance:
raise InsufficientBalanceError("Not enough balance.")
This makes your application logic clearer and more structured.
BEST PRACTICES
• Inherit from Exception
• Use meaningful class names
• Provide clear error messages
• Use custom exceptions for specific business logic
KEY TAKEAWAY
Custom exceptions allow you to define and handle application-specific errors clearly and professionally, making your Python programs stronger and easier to maintain.