Python chapters

Chapter 13 of 17

Error Handling

Try this in our Python 3 Compiler →

Things go wrong

Files are missing, networks drop, users type nonsense, divisions land on zero. A robust program anticipates errors and handles them, instead of crashing in the user's face. Error reporting differs by language: exceptions, explicit return values and result types require different handling. Check the example and language notes before choosing a recovery strategy.

try:
    n = int("not a number")
except ValueError as e:
    print("Bad input:", e)

When to catch

Only catch errors you actually know how to recover from. Catching and then ignoring an error is the single most common cause of mysterious bugs in production systems — the program keeps going as if everything were fine while the data is silently broken.

Logging

Whenever you catch an error, log it with enough context (what you were trying to do, with what inputs) that someone reading the log later can understand what happened. Modern apps live or die by the quality of their logs.

Details for python

ValueError can mean invalid numeric input. EOFError means input() requested a line after supplied stdin ended. FileNotFoundError means a file is absent; an online run cannot see files on your computer.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on