~/learn/Python · Classes & structure

Errors and testing

Fail clearly, then prove your code is right.

8 min readlesson 23 of 23tryraiseassert

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.

python · editable
loading editor…

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.

python · editable
loading editor…

A test is just a function that asserts the expected result. Writing a handful for your transformations catches regressions long before production does.

python · editable
loading editor…

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.