Hone

Lessons · Python · try / except

Plan for the failure

try runs code that might fail; except catches a specific error and lets you decide what happens instead of crashing.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Files go missing, input is garbage, networks drop. Code that expects that and recovers is the difference between a tool and a toy.

How to think about it

Which line can fail, and with which error? Wrap the smallest possible piece of code, catch the specific error you expect (ValueError, not a bare except), and decide the fallback. If you cannot handle it sensibly, let it raise.

Worked example

try:
Only the risky line inside.
    n = int(text)
Might raise ValueError.
except ValueError:
Only that error. Others still surface.
    n = 0
The fallback you chose.

Your turn

Catch a missing key and use a default.

try:
    v = settings["theme"]
except :
    v = "light"

The trap

A bare except: catches everything, including the Ctrl-C to stop the program and the typo in your own code. Name the error.

Practise try / except on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.