Built-in errors like
ValueError and TypeError are useful, but they often hide the real problem. When your program fails because a user has no credit left, or an item is out of stock, you want a name that means something to you. That is where custom exceptions come in.Defining the minimum
class InsufficientFunds(Exception):
"""Raised when there is not enough money."""
try:
raise InsufficientFunds("Not enough money")
except InsufficientFunds as e:
print(e)Why specific names beat generic catches
Catching
Exception for everything is like putting a plaster on every cut. If your function can fail because the port is wrong, or because the file does not exist, you want two different names so callers know exactly what went wrong and how to react.Exception families
class ShopError(Exception):
"""Base for all shop-related problems."""
class OutOfStock(ShopError):
pass
def buy(item, qty=1):
if item == 'coffee':
raise OutOfStock("Coffee is gone")
return f'Purchased {qty} x {item}'
try:
buy('coffee')
except ShopError as e:
print(f"Shop problem: {e}")Because
OutOfStock inherits from ShopError, a single except ShopError catches both. This keeps your error handling tidy when you have many related failure modes.Chaining errors with from
class ConfigError(Exception):
pass
def read_level(settings):
try:
value = settings['level']
except KeyError as err:
raise ConfigError('no level') from err
try:
return int(value)
except ValueError as err:
raise ConfigError('bad level') from err
print(read_level({'level': '3'})) # 3
fromraise ... from err swaps Python's error for yours, and keeps the original as its cause, so the traceback shows both: Python's error first, then yours. Each step has its own try, so each problem gets its own message.