Course outline · 0% complete

0/32 lessons0%

Course overview →

try / except

lesson 9-2 · ~11 min · 28/32

Handling errors instead of crashing

Some errors are not bugs, they are expected: users type nonsense, files go missing. A try/except block lets you attempt risky code and take a recovery path when a specific error occurs:

try:
    n = int(raw)
    print("ok:", n)
except ValueError:
    print("bad:", raw)

How it flows: Python runs the try block. If nothing goes wrong, except is skipped entirely. If the named error is raised anywhere in the try, Python abandons the rest of the block and jumps into the except.

Two rules of good taste:

  1. Name the error (except ValueError:). A bare except: also swallows real bugs like typos, hiding them from you.
  2. Keep the try small: only the line(s) that can legitimately fail.

Code exercise · python

Run this. The same conversion code handles good and bad input without crashing.

Quiz

In a try/except ValueError block, what happens when the try body raises a KeyError?

Code exercise · python

Your turn. Write `safe_div(a, b)` that returns `a / b`, but returns `0` if b is zero, using try/except ZeroDivisionError. The two prints should show 5.0 and 0.

Code exercise · python

One more, with real input. Read a line, try to convert it to an int and print `double: ` and twice the number, or print `please type a number` if the conversion fails. The stdin here contains `hello`, so the except path should run.