Python Foundations · Objects & reliability
Errors, exceptions & tests
Fail loudly and on purpose: raise, catch, and prove your code works with pytest.
Step 1 of 5 · 1. try / except15 min read ·
1. try / except
from decimal import Decimal, InvalidOperation
def parse_px(s):
try:
return Decimal(s)
except InvalidOperation:
raise ValueError(f"bad price: {s!r}")Catch the specific exception you expect. A bare except: hides real bugs, which in a recon job means silently dropping trades.
Next: 2. Tests with pytest