Part 06 / Topic 10 of 10
Good practices
- ❌ Do not use a bare
except:. It even catchesCtrl+Cand hides real bugs. - ✅ Catch the narrowest exception you expect (
ValueError, notException). - ✅ Keep the
tryblock small: only the line that can fail. - ✅ Give helpful messages: say what was wrong and what is expected.
- ✅ Do not silently
passon errors. At least print or log something. - ✅ Use
finally(orwith, taught in Part 8) for clean-up.
# Bad: big try, bare except, silent
# try:
# qty = int(text)
# total = qty * price
# save(total)
# except:
# pass
# Good: small try, specific error, clear message
text, price = "3", 40
try:
qty = int(text)
except ValueError:
print("Quantity must be a whole number")
else:
print("Total:", qty * price) # Total: 120
Done here? The practice set for Part 6 — 7 exercises with solutions — is on the part page.