Python Files & Errors
Python Custom Exceptions
Custom exceptions let you create your own, meaningfully named error types for the specific problems your program can run into, instead of reusing generic built-in ones everywhere.
Why Create Custom Exceptions?
A generic ValueError does not tell the reader much about your application. A custom exception like InsufficientBalanceError or InvalidRollNumberError instantly communicates intent, and lets calling code catch exactly that situation without accidentally catching unrelated errors.
Creating a Custom Exception
You create a custom exception by defining a class that inherits from Exception (or one of its built-in subclasses). Often the class body is just "pass" because it inherits all the behaviour it needs.
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError("Not enough balance for this withdrawal")
return balance - amount
withdraw(1000, 5000)Adding a Custom Message and Data
You can override __init__ to store extra details on the exception object, like the offending value, which makes debugging and logging far more useful.
class InvalidMarksError(Exception):
def __init__(self, marks):
self.marks = marks
super().__init__(f"Invalid marks: {marks}. Must be between 0 and 100.")
try:
raise InvalidMarksError(150)
except InvalidMarksError as e:
print(e)
print("Bad value was:", e.marks)Always call super().__init__(message) so print(exception) and the traceback still show a readable message.
Building an Exception Hierarchy
For larger applications, define one base exception for your app, then subclass it for specific cases. This lets callers catch broadly (catch AppError to handle any app-specific problem) or narrowly (catch just InvalidRollNumberError).
class AppError(Exception):
"""Base class for all custom errors in this app."""
pass
class InvalidRollNumberError(AppError):
pass
class StudentNotFoundError(AppError):
pass
try:
raise StudentNotFoundError("No student with roll number 42")
except AppError as e:
print("App-level problem:", e)- Subclass Exception (or a specific built-in) to define a custom error type.
- Override __init__ and call super().__init__() to attach a clear message.
- Group related custom exceptions under one base class for flexible catching.
- Custom exceptions make your code self-documenting and easier to maintain.
