Sub topic 2
Catching errors with try and except
This chapter assumes you can write and call functions, use if, for, and while, and read a simple traceback. It covers the basic try/except statement. Handler ordering, else, and finally come in later chapters.
The working model
When an operation fails, Python raises an exception. It abandons the current statement and looks for an enclosing try statement with a matching except clause. It checks the current function first, then the caller, then the caller's caller. If no handler matches anywhere, the program stops and prints a traceback.
A try statement marks a region where you are prepared to handle specific failures.
def read_age(text):
try:
age = int(text)
except ValueError:
print(f"{text!r} is not a whole number")
return None
return age
print(read_age("42"))
print(read_age("forty"))The first call prints 42. In the second call, int("forty") raises ValueError. The handler prints a message and returns None.
Execution does not resume
When an exception is raised, the rest of the try body is skipped. After the handler finishes, execution continues after the whole try statement. It does not go back to the line that failed.
try:
print("before")
value = int("x")
print("never printed")
except ValueError:
print("handled")
print("after")This prints before, handled, and after. If you need to retry, wrap the try in a loop.
Keep the try body small
Only the statements that can raise the error you expect belong in the try body. A wide body can catch an error from an unrelated line and hide a bug.
def average(values):
try:
return sum(values) / len(values)
except ZeroDivisionError:
return 0.0Here the handler is meant for an empty list. If values contained strings, sum would raise TypeError, which this handler does not match. The bug stays visible instead of being silently turned into 0.0.
To handle several unrelated types the same way, name them in a tuple: except (KeyError, IndexError):.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Bare `except:` | Also catches `KeyboardInterrupt` and `SystemExit`, so Ctrl+C may stop working | Name the types, or use `except Exception:` as a last resort |
| `except Exception: pass` | Failures vanish with no trace | Handle the error, or log it and re-raise |
| Large `try` body | Handler catches errors from lines you did not mean to cover | Wrap only the risky call |
| `except A, B:` | `SyntaxError` in Python 3 | Use a tuple: `except (A, B):` |
| Expecting the body to resume | Lines after the failing one never run | Loop around the `try` to retry |
Choosing what to catch
Catch an exception only when you can do something useful about it. You might substitute a default, ask for new input, or translate it into a clearer error. Otherwise leave it alone. Callers higher up may know better how to respond, and the top-level traceback shows exactly where the failure occurred.
Exercise
What does this code print, and why? try: print("a") result = 10 / 0 print("b") except ZeroDivisionError: print("c") print("d")
Show answer
It prints a, c, d. "a" prints before the failure. 10 / 0 raises ZeroDivisionError, so "b" is skipped. The matching handler prints "c". Execution then continues after the try statement and prints "d".
Exercise
Why is except: with no exception type risky, and what is a safer alternative when you do not know the exact type?
Show answer
A bare except also catches KeyboardInterrupt and SystemExit, which should normally end the program. A safer choice is except Exception:, which skips those two. Naming the specific types you expect is better still.