Python › Exception Handling
How do you create a custom exception class, and what's the minimal amount of code needed?
IntermediateAnswer
Define a class inheriting from Exception (or a more specific built-in exception), typically with no additional code needed at all (just 'pass') unless you want to add custom attributes or override __init__ — Python's exception machinery handles the rest automatically via inheritance.
class InsufficientFundsError(Exception):
def __init__(self, shortfall):
super().__init__(f"Insufficient funds. Short by ${shortfall:.2f}")
self.shortfall = shortfall
try:
raise InsufficientFundsError(50.00)
except InsufficientFundsError as e:
print(e.shortfall) # 50.0Real-world example Raising a domain-specific exception (like InsufficientFundsError) that carries meaningful business context beyond a generic message.