Raise and Define Custom Exceptions
Core idea
raise signals a failure instead of returning a normal result. Choose a built-in exception when it describes the problem; define a custom class when callers need to distinguish a domain-specific failure. class StockError(Exception): pass creates a subclass with inherited exception behavior; classes are studied later.
def reserve(count): if count < 0: raise ValueError("negative count") return count * 2print(reserve(3))Valid input returns a result; negative input violates the contract.
Custom failure
class StockError(Exception): passdef take(count): if count > 5: raise StockError("not enough stock") return counttry: take(7)except StockError as error: print(str(error))The caller recognizes a stock-specific failure and reads its message.
Intentional unhandled failure
This intentionally fails with ValueError; it is not a successful output example.
Common mistake
Returning an error string from a function that promises an integer mixes incompatible success and failure results. Prefer a documented exception when the operation cannot complete.
Practice
Define CapacityError derived from Exception; raise it when a requested count exceeds 10, and catch it at the call site.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Define a failure contract
Check your understanding of raise and custom exceptions.
What happens?
raise ValueError("bad count")What is printed?
class StockError(Exception): passprint(issubclass(StockError, Exception))What is printed?
class StockError(Exception): passtry: raise StockError("full")except StockError as error: print(str(error))When is a custom exception helpful?