Custom Exception Inventory

Custom Exception Inventory

Built-in exceptions don't always describe your problem precisely. You can define your own by subclassing Exception.

Define an exception class InsufficientStockError (subclassing Exception), then write:

remove_stock(stock, amount)

If amount is greater than stock, raise InsufficientStockError. Otherwise, return stock - amount.

Examples

remove_stock(10, 4)    // → 6
remove_stock(10, 10)   // → 0
remove_stock(10, 15)   // raises InsufficientStockError

Walkthrough

Thinking it through

Built-in exceptions like ValueError are generic on purpose — they describe a shape of problem ("bad value"), not your specific domain. When you're modeling something like an inventory system, a custom exception class communicates intent far better than reusing ValueError for everything.

Defining a custom exception

class InsufficientStockError(Exception):
    pass

That's the entire definition. Subclassing Exception gets you everything a normal exception needs — a message, a traceback, the ability to be caught by type — for free. You don't need to override __init__ unless you want extra structured data on the exception itself (some problems later in this course will).

Using it

Once defined, you raise and catch it exactly like a built-in:

if amount > stock:
    raise InsufficientStockError(f"only {stock} in stock, tried to remove {amount}")

Why this matters

As programs grow, catching except InsufficientStockError: specifically (rather than a generic except ValueError: or, worse, except Exception:) means calling code can respond precisely to this failure mode without accidentally swallowing unrelated bugs that also happen to raise ValueError.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.