Custom Exceptions
1. What Are Custom Exceptions?
Sometimes, the built-in exceptions like ValueError or IndexError aren’t enough to describe a specific problem in your program. In such cases, you can create your own exception class—these are called custom exceptions.
Why use them?
-
To make your error messages more meaningful.
-
To differentiate between different types of errors in complex programs.
-
To improve readability and maintainability of code.
2. Creating a Custom Exception
In Python, all exceptions must inherit from the built-in Exception class (or one of its subclasses).
Basic Example
Explanation:
-
class NegativeAgeError(Exception):→ This creates a new exception type. -
raise NegativeAgeError("message")→ This triggers the exception if the condition is met.
Catching Custom Exceptions
Just like built-in exceptions, custom exceptions can be caught with try-except:
Output example:
3. Adding More Details to Exceptions
You can add an __init__ method to include extra information, like the value that caused the error:
Output example:
This makes debugging much easier because you know exactly what went wrong.
4. Best Practices for Custom Exceptions
-
Inherit from Exception:
Avoid inheriting directly fromBaseException. -
Use meaningful names:
Example:InvalidTransactionErroris clearer than justError. -
Add extra info if needed:
Include values or context that help debug. -
Keep them specific:
Don’t create one generic exception for everything; it defeats the purpose.
5. Real-Life Example: Bank Transaction
Imagine a banking program:
Output:
-
The custom exception clearly communicates why the operation failed.