Hone

Lessons · Python · bare except

Catch the error you expect

A bare except: catches everything, including typos, Ctrl-C and memory errors. Name the exception you mean: except ValueError:.

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

A bare except turns a crash that would have shown the bug into silence and a wrong answer. The report says zero rows instead of the traceback that would have taken a minute to fix.

How to think about it

Ask what can actually go wrong here, and catch that. Let everything else stay loud. If you truly must catch all, catch Exception and log it, so the failure has a record.

Worked example

def f(text):
A small parser.
    try:
The risky line.
        return int(text)
Fails on text that is not digits.
    except ValueError:
Only the failure we expect.
        return 0
A sensible fallback for bad input, and nothing else.
print(f("12"), f("x"))
12 0: bad input handled; any other error would still raise, as it should.

Your turn

Handle a missing file only.

try:
    data = open(path).read()
except :
    data = ""

The trap

except: also swallows KeyboardInterrupt, so a stuck program cannot be stopped with Ctrl-C. That alone is reason enough never to write it.

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