Back to results for “Exception Handling”
Python › Exception Handling

How do you create a custom exception class, and what's the minimal amount of code needed?

Intermediate

Answer

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.0
Real-world example Raising a domain-specific exception (like InsufficientFundsError) that carries meaningful business context beyond a generic message.

Common follow-ups: Why is it good practice to inherit custom exceptions from a specific built-in type rather than always using the bare 'Exception'?