Medium: Interview Core · Problem 53 of 82

A Custom Exception

MediumErrors and FilesPython

Write:

  1. an exception class InsufficientFunds that inherits from Exception, is created as InsufficientFunds(needed, available), keeps both numbers as attributes needed and available, and has the message "need 20 more" (for needed=20),
  2. a function withdraw(balance, amount) that returns the new balance, or raises InsufficientFunds with needed set to the missing amount and available set to the balance. A negative amount raises ValueError.

Understand the problem

Revise how exceptions carry information.

Why create your own exception class instead of raising ValueError("not enough money")?

  1. It is shorter
  2. Callers can catch exactly this error, and it can carry data such as how much is missing
  3. Python requires it

A specific class lets callers write except InsufficientFunds as e: and read e.needed. With a text message they would have to parse the text. Custom exceptions are part of an API.

In class MyError(Exception), how do you make str(error) give a message you choose?

  1. Set self.message
  2. Call super().__init__(message) in your __init__
  3. Define __print__

str(exception) shows the arguments given to Exception.__init__. Pass the message to super().__init__(...), and also store any extra fields as attributes.

Write the solution

Write the exception class and the function.

class InsufficientFunds(Exception):
    # Write your code here.
    pass

def withdraw(balance, amount):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What information would a caller want from this error, and where do you store it?

Hint 2: the shape of the answer

In __init__(self, needed, available): call super().__init__(f"need {needed} more") and set self.needed and self.available. In withdraw, check the amount, then compare with the balance.

Reflect

Solution

class InsufficientFunds(Exception):
    def __init__(self, needed, available):
        super().__init__(f"need {needed} more")
        self.needed = needed
        self.available = available


def withdraw(balance, amount):
    if amount < 0:
        raise ValueError("amount cannot be negative")
    if amount > balance:
        raise InsufficientFunds(amount - balance, balance)
    return balance - amount

What this tests: subclassing Exception, super().__init__, attributes on exceptions, raise, and choosing between built-in and custom exceptions.

Inherit from the right class. From Exception (or a more specific subclass such as ValueError) so that except Exception still works. Never inherit from BaseException for ordinary errors.

A family of errors: libraries define one base class (class BankError(Exception)) and subclasses of it, so callers can catch all of them with one except BankError, or just the one they care about.

When a built-in is enough: use ValueError, KeyError, TypeError for ordinary misuse. Make your own when callers need to tell this situation apart from the rest, or when it carries data.

What an interviewer might ask next: Make InsufficientFunds a subclass of ValueError and discuss the trade-off. (Existing except ValueError handlers would then also catch it, which may or may not be what you want.)