User Defined Exceptions
Definition
A user defined exception is an exception class created by the programmer to represent a specific error condition in an application that is not sufficiently covered by built-in exceptions.
In most programming languages, user defined exceptions are created by:
- defining a new exception class,
- inheriting from the language’s base exception type,
- and raising that exception when a specific error condition occurs.
Example idea:
- If a student age is below an allowed minimum, a custom exception like
InvalidAgeExceptioncan be raised. - If a password is too weak, a custom exception like
WeakPasswordExceptioncan be raised.
Main Content
1. Need for User Defined Exceptions
User defined exceptions are needed when built-in exceptions do not clearly describe the problem in the context of the application.
Application-specific error reporting
- Built-in exceptions usually describe technical issues such as divide-by-zero, null reference, file not found, or invalid index.
- However, real applications often need to express business rules and domain logic more clearly.
- Example: In a library system, if a user tries to issue more than the allowed number of books, the error is not a technical failure but a rule violation. A custom exception such as
BookLimitExceededExceptionis more meaningful.
Improved clarity and maintainability
- Custom exceptions make code easier to understand because the exception name itself explains the problem.
- Instead of using a generic exception for every issue, developers can identify exactly what went wrong and where.
- This becomes very helpful in debugging, logging, and long-term maintenance.
Better control over program behavior
- A custom exception allows a program to react differently to different kinds of errors.
- Example:
InsufficientFundsExceptionmay prompt a retry, whileAccountLockedExceptionmay require user verification. - This leads to cleaner and more intelligent error handling.
Example:
class InvalidAgeException(Exception):
pass
age = 15
if age < 18:
raise InvalidAgeException("Age must be 18 or above.")
In this example, the exception directly represents the rule being broken.
2. Creation and Structure of User Defined Exceptions
Creating a user defined exception usually involves defining a class that extends the language’s built-in exception class.
Inheritance from a base exception class
- Most languages provide a root exception class, such as
Exception. - By inheriting from it, the custom exception becomes compatible with standard exception-handling mechanisms like
try,catch, andraise. - This ensures the exception can be thrown and caught like any other error.
Adding meaningful data and behavior
- A custom exception can store additional information, such as error code, invalid value, or field name.
- This extra data helps in debugging and in showing useful messages to the user.
- Example: a
NegativeBalanceExceptionmay store the invalid balance amount.
Custom messages and constructors
- Custom exceptions often include constructors or initialization methods to pass descriptive messages.
- This makes the exception more flexible because different situations can produce different messages.
- Example:
raise WeakPasswordException("Password must contain at least 8 characters.")
Basic structure example:
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(message)
Using the exception:
raise CustomError("Something went wrong in the application.")
Conceptual structure:
Base Exception
|
v
User Defined Exception
|
v
Specific Exception Classes
This structure shows how custom exceptions are built on top of the standard exception hierarchy.
3. Handling User Defined Exceptions
Once a custom exception is created, it must be handled properly so the program does not terminate unexpectedly.
Throwing or raising the exception
- The program checks a condition, and if the condition indicates an invalid state, it raises the custom exception.
- This separates normal execution from exceptional cases.
- Example: if a student marks are outside the valid range, raise
MarksOutOfRangeException.
Catching the exception
- The exception is caught in a
try-catchortry-exceptblock. - The handler can display a message, log the issue, ask for corrected input, or perform cleanup.
- This helps the program recover gracefully.
Multiple custom exceptions
- A program can define many custom exceptions for different error conditions.
- Each exception can be handled separately to take the correct action.
- Example:
InvalidEmailException,PasswordMismatchException, andUserNotFoundExceptioncan all be handled in different ways.
Example:
class InsufficientBalanceException(Exception):
pass
try:
balance = 500
withdraw = 1000
if withdraw > balance:
raise InsufficientBalanceException("Withdrawal amount exceeds balance.")
except InsufficientBalanceException as e:
print(e)
Flow of handling:
Check condition -> Raise custom exception -> Catch exception -> Display/log/resolve issue
This flow ensures that errors are not ignored and are handled in a controlled manner.
Working / Process
1. Identify the special error condition
- Determine which application rule or condition needs a custom exception.
- Example: invalid age, insufficient balance, duplicate record, or unauthorized access.
2. Define the custom exception class
- Create a new class that extends the base exception class.
- Add a message or extra information if required.
3. Raise and handle the exception
- When the condition occurs, raise the custom exception.
- Catch it where appropriate and handle it by showing an error message, logging it, or taking corrective action.
Advantages / Applications
Clear and meaningful error messages
- Custom exceptions describe the exact problem in terms related to the application.
- This makes error handling easier to understand for both developers and users.
Better modularity and maintainability
- Each type of error can be handled separately.
- This keeps the code organized and reduces confusion in large programs.
Wide use in real-world applications
- User defined exceptions are common in banking systems, e-commerce platforms, educational software, healthcare systems, and API development.
- They are used to enforce business rules such as credit limits, stock availability, valid age, password strength, and payment validation.
Summary
- User defined exceptions are custom errors created by programmers for specific application needs.
- They help represent business rules and special conditions more clearly than built-in exceptions.
- They are defined by creating a class from the base exception type and then raising and handling it when needed.
- Important terms to remember: exception, user defined exception, raise, catch, handler, custom exception