Editor

Your Own Exception Class

#587 · Errors and exceptions · Intermediate · 60 XP · about 10 min

Python's own exceptions, such as ValueError, say what kind of thing went wrong. A class of your own can say it more precisely and carry the details with it.

Write the class OutOfStockError, a subclass of Exception, for a shop that runs out of things:

  • OutOfStockError(item, wanted, have) stores its three arguments as the attributes item, wanted and have.
  • Its message, which str(error) gives, is 'Only 2 pens left, 5 wanted' with the real values, or 'No pens left, 5 wanted' when have is 0.

Pass the message to super().__init__(message), so the Exception part of your class knows it. The function take is provided: it raises your exception when the shop does not have enough.

Examples

take({'pens': 9}, 'pens', 4)  # returns 5, the pens left

try:
    take({'pens': 2}, 'pens', 5)
except OutOfStockError as e:
    print(e)       # Only 2 pens left, 5 wanted
    print(e.have)  # 2

take({}, 'glue', 1)  # raises OutOfStockError: No glue left, 1 wanted

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.