~/learn/Python · Classes & structure
Errors and testing
Fail clearly, then prove your code is right.
why this matters
Code that fails loudly and clearly costs minutes to debug; code that fails silently costs days. Tests are how you prove a fix stays fixed.
try/except handles a failure you expect. Catch the specific exception type, not a bare except, so real bugs still surface.
Try it: Make it also accept strings with surrounding whitespace.
raise signals a problem the caller must deal with, and else/finally round out the block: else runs when nothing failed, finally always runs.
A test is just a function that asserts the expected result. Writing a handful for your transformations catches regressions long before production does.
try / except
try: attempt the risky thing except ValueError: handle what you expect finally: always run (cleanup)
Common gotcha
Never write a bare `except:` — it swallows typos and interrupts too. Catch the specific error you expect.
Pro tip
Write the failing test first, then the fix. It proves the test actually catches the bug.
key takeaways
- Catch specific exception types, not everything.
- raise your own errors with a clear message.
- A test is just an assert about known input and output.
check your understanding
Why is a bare `except:` a bad idea?
free practice
Build confidence with a question you can solve without Pro.