Sub topic 2
Catching errors with try and except
This chapter assumes you can write and call Python functions, use if, for, and while, and read a simple traceback. It covers the core try/except statement: how it runs, how far its reach extends, and the mistakes people most often make with it. Later chapters cover handler ordering, else, and finally in more detail.
The basic shape
A try statement wraps code that might fail. If an exception is raised inside the try block, Python stops running that block and looks for a matching except clause. If it finds one, it runs the handler and then continues after the whole statement.
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-two"))
print("program still running")The output is:
42
'forty-two' is not a whole number
None
program still runningWithout the try, the second call would end the program with a traceback. With it, the ValueError raised by int() is intercepted, and the program carries on.
What happens step by step
The rules are short, but each one matters.
- Python runs the statements in the
tryblock from top to bottom. - If none of them raises, every
exceptclause is skipped. - If one raises, the rest of the
tryblock is abandoned immediately. Statements after the failing line never run. - Python compares the exception against each
exceptclause in order and runs the first one that matches. - If no clause matches, the exception keeps propagating to the caller.
Step 3 has a consequence people forget. Any variable assigned only inside the try block may not exist if the exception fires first.
def read_age(text):
age = None
try:
age = int(text)
except ValueError:
print("invalid age")
return age
print(read_age("x"))If age = None were missing, the return age line would raise UnboundLocalError for bad input. Either initialize the variable before the try, or return from inside the handler as the first example does.
Handlers catch what is raised below them
The try block covers more than the lines you can see in it. It also covers every function those lines call, however deep. An exception travels up the call stack until a handler matches.
def parse(text):
return int(text)
def average(values):
return sum(parse(v) for v in values) / len(values)
try:
print(average(["4", "x", "8"]))
except ValueError as exc:
print("could not average:", exc)The ValueError is raised inside parse, passes through the generator expression and average, and is caught at the top. Neither parse nor average needed any error-handling code. This is the main reason to catch exceptions at the level where you know how to respond, which is often far from where they were raised.
A function that does not know how to recover should usually not catch the error at all.
Keep the try block small
A common intermediate mistake is wrapping a whole function body in one try. Compare these two versions.
import json
def load_settings(path):
# Too wide: any ValueError from anywhere in here is treated the same way
try:
with open(path) as f:
data = json.load(f)
port = int(data["port"])
return {"port": port}
except ValueError:
return {"port": 8080}This handler claims to deal with a bad port number. But json.load can also raise json.JSONDecodeError, which is a subclass of ValueError. A corrupt file would silently give you the default port, and the real problem would be hidden.
A narrower version names the risky operation and lets other errors surface.
import json
def load_settings(path):
with open(path) as f:
data = json.load(f)
try:
port = int(data["port"])
except ValueError:
port = 8080
return {"port": port}Now the handler covers only the int() call. A malformed file still raises, and the caller sees the true cause. The rule of thumb is that the try block should contain the one operation whose failure you have a plan for.
Choosing what to catch
You can name more than one type in a single clause by using a tuple.
def to_number(value):
try:
return float(value)
except (TypeError, ValueError):
return None
print(to_number("3.5"))
print(to_number("abc"))
print(to_number(None))float("abc") raises ValueError, and float(None) raises TypeError. Both get the same response here, so one clause handles them. If they needed different responses, you would write two clauses, and the order would matter. That is the subject of the chapter on multiple handlers.
Always catch the most specific type you can justify. The table shows how the choices compare.
| Clause | What it catches | Typical verdict |
|---|---|---|
| `except ValueError:` | Only `ValueError` and its subclasses | Good. States the failure you expect. |
| `except (KeyError, IndexError):` | Either lookup failure | Good when both get the same response. |
| `except Exception:` | Nearly every error from ordinary code | Acceptable at a program boundary, such as a request handler or job runner. |
| `except:` | Everything, including `KeyboardInterrupt` and `SystemExit` | Avoid. It blocks Ctrl+C and normal shutdown. |
Swallowing errors
The worst try statement is one that catches an error and does nothing useful with it.
def save(record):
try:
write_to_disk(record)
except Exception:
passIf write_to_disk fails, the program continues as though the record was saved. The failure shows up later as missing data, with no traceback to point at the cause. When you catch an exception, do at least one of these things:
- Recover, for example by using a default value or retrying.
- Report it, for example by logging it with its traceback.
- Re-raise it so a caller with more context can decide.
Silencing an error is occasionally correct, but it should be a deliberate choice that you can explain in a comment.
Catching versus checking first
You can often avoid an exception by testing a condition first, or by catching the exception afterward. Python programmers generally prefer the second style. It is summarized as "easier to ask forgiveness than permission".
# Look before you leap: two lookups, and a race if another thread changes the dict
if "name" in config:
name = config["name"]
else:
name = "anonymous"
# Ask forgiveness: one lookup
try:
name = config["name"]
except KeyError:
name = "anonymous"For a plain dictionary, config.get("name", "anonymous") is simpler still. Catching an exception is the better fit when the check duplicates the work of the operation itself, or when the state could change between the check and the use. Examples are opening a file that might have been deleted, or parsing text whose validity is only known by trying. When failure is common and a simple test exists, an if is clearer and cheaper, because raising and catching an exception costs more than a comparison.
Common errors
- Wrapping too much code. The handler then catches failures you did not anticipate. Shrink the
tryblock. - Catching
Exceptiondeep inside library code. Low-level functions rarely know the right response. Let errors propagate. - Using a bare
except:. It catches shutdown signals as well as errors. - Assuming a variable was set. Names assigned in a failed
tryblock may not exist afterward. - Printing instead of handling. A handler that only calls
printand then falls through often leaves the program in a half-finished state.
Exercise
This function is meant to return a default of 0 when text is not a valid integer. It has two problems. What are they, and how would you fix them?
def to_int(text):
try:
print("converting")
value = int(text)
total = value * 2
return total
except:
return 0
Show answer
First, the bare except: catches everything, including KeyboardInterrupt and SystemExit. Use except ValueError:. Since int(None) raises TypeError, use except (TypeError, ValueError): if None is a possible input. Second, the try block is too wide. Only int(text) can fail in the way the default is meant to cover, so move the other lines out. A corrected version is: try: value = int(text) / except ValueError: return 0 / return value * 2.
Exercise
In the code below, what is printed, and why is the line print("after") inside the try never reached?
try:
numbers = [1, 2, 3]
print(numbers[5])
print("after")
except IndexError:
print("out of range")
Show answer
It prints out of range. The expression numbers[5] raises IndexError, so Python abandons the rest of the try block at once. The print("after") line is skipped, the matching except IndexError handler runs, and execution continues after the statement.