A Custom Exception
Write:
- an exception class
InsufficientFundsthat inherits fromException, is created asInsufficientFunds(needed, available), keeps both numbers as attributesneededandavailable, and has the message"need 20 more"(forneeded=20), - a function
withdraw(balance, amount)that returns the new balance, or raisesInsufficientFundswithneededset to the missing amount andavailableset to the balance. A negativeamountraisesValueError.
Understand the problem
Revise how exceptions carry information.
Why create your own exception class instead of raising ValueError("not enough money")?
- It is shorter
- Callers can catch exactly this error, and it can carry data such as how much is missing
- 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?
- Set
self.message - Call
super().__init__(message)in your__init__ - 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.)
VISIBLE = 3
CASES = [
('try:\n withdraw(10, 30)\nexcept InsufficientFunds as e:\n result = (e.needed, e.available, str(e))', (20, 10, 'need 20 more'), 'the error carries the numbers and a message'),
('result = withdraw(50, 20)', 30, 'a normal withdrawal'),
('result = withdraw(10, 10)', 0, 'taking everything'),
('result = error_of(withdraw, 5, -1)', 'ValueError', 'a negative amount'),
('result = issubclass(InsufficientFunds, Exception)', True, 'it is an Exception'),
('result = error_of(withdraw, 0, 1)', 'InsufficientFunds', 'an empty account'),
('e = InsufficientFunds(7, 3)\nresult = (e.needed, e.available, str(e))', (7, 3, 'need 7 more'), 'created directly'),
('try:\n withdraw(1, 100)\nexcept Exception as e:\n result = isinstance(e, InsufficientFunds)', True, 'it can be caught as Exception'),
]