How do you manually raise and customize an exception in Python? | A1Lab@MZeeshanM to PythonEnglish • 7 days ago

How do you manually raise and customize an exception in Python?

message-square
0

Use the raise keyword with an instance of a built-in exception (such as ValueError("message")) to trigger an error manually, or define a new class inheriting from Exception to create domain-specific custom exceptions with tailored attributes and error messages.

Basic Example

# 1. Define a custom exception by subclassing Exception (not BaseException)
class InsufficientFundsError(Exception):
    def __init__(self, balance: float, amount: float):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Cannot withdraw ${amount:.2f}; current balance is ${balance:.2f}")

# 2. Raise built-in and custom exceptions using the 'raise' keyword
def withdraw(balance: float, amount: float) -> float:
    if amount <= 0:
        raise ValueError("Withdrawal amount must be greater than zero")
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

# 3. Catch and inspect the custom exception's structured attributes
try:
    withdraw(50.0, 120.0)
except InsufficientFundsError as err:
    print(err)                                # Output: Cannot withdraw $120.00; current balance is $50.00
    print(f"Shortfall: ${err.amount - err.balance:.2f}")  # Output: Shortfall: $70.00

Key Details & Patterns

  • Always inherit from Exception (never BaseException): Subclassing BaseException directly causes except Exception: blocks to miss your custom error and mixes your application logic with system-exit signals like KeyboardInterrupt and SystemExit.
  • Exception chaining (raise ... from ...): When catching a low-level error (like a KeyError or database failure) and raising a higher-level custom exception, use from to preserve the original traceback—or from None to suppress noisy internal tracebacks:
    class ConfigError(Exception):
        pass
    
    def load_port(config: dict) -> int:
        try:
            return int(config["port"])
        except KeyError as exc:
            raise ConfigError("Missing required 'port' setting") from exc
    
  • Re-raising the active exception (raise with no arguments): Inside an except block, a bare raise statement re-throws the exact caught exception while keeping its original stack trace intact (ideal for logging errors before letting them propagate).
  • Building a hierarchy of custom exceptions: For larger packages or APIs, define a single base error class (e.g., class PaymentError(Exception): pass) and inherit specific subclasses from it (class CardDeclinedError(PaymentError): pass), allowing callers to catch either specific failures or all module errors at once.

Common Built-in vs. Custom Exception Choices

Exception Class When to Raise Example Trigger
ValueError Argument has the right type, but an invalid value withdraw(100, -5)
TypeError Argument has an unsupported data type Passing a str where an int is required
RuntimeError Generic state error that doesn’t fit another category Calling .send() before .connect()
Custom Exception subclass Domain-specific failure or when callers need structured error metadata InsufficientFundsError(balance, amount)