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.
remove_stock(10, 4) // → 6
remove_stock(10, 10) // → 0
remove_stock(10, 15) // raises InsufficientStockError
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.
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).
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}")
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.
class InsufficientStockError(Exception):
pass
def remove_stock(stock, amount):
if amount > stock:
raise InsufficientStockError(f"only {stock} in stock, tried to remove {amount}")
return stock - amount
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.