Errors and try/except

Python · Essentials · 8 min

Programs meet bad input and missing files; handling errors deliberately keeps them from crashing.

When something goes wrong Python raises an exception. If nothing handles it, the program stops and prints a traceback. Read it from the bottom up: the last line names the exception type and message (ValueError: invalid literal for int() with base 10: 'abc'), and the lines above show the chain of calls, with the most recent call last.

Common built-in exceptions: ValueError (right type, bad value), TypeError (wrong type), KeyError, IndexError, ZeroDivisionError, FileNotFoundError, AttributeError and NameError.

A try block lets you handle an exception you expect:

try:
    n = int(text)
except ValueError:
    n = 0

Only the code that might fail should be inside try, and you should catch the specific exception you can handle. A bare except: or except Exception: that silently continues hides real bugs, including typos. Use except ValueError as e: to get the exception object, for example to log e.

Python favours EAFP — "easier to ask forgiveness than permission": try the operation and handle failure, rather than checking every precondition first. It avoids race conditions (a file can vanish between the check and the open) and keeps the happy path clean.

Raise your own exceptions with raise ValueError("age must be positive") when a function receives input it can't work with. A clear error at the source beats a confusing failure three calls later.

Example

def parse_age(text):
    age = int(text)              # may raise ValueError
    if age < 0:
        raise ValueError(f"age must be >= 0, got {age}")
    return age

for raw in ["42", "abc", "-5"]:
    try:
        print("ok:", parse_age(raw))
    except ValueError as e:
        print("bad input:", e)
# ok: 42
# bad input: invalid literal for int() with base 10: 'abc'
# bad input: age must be >= 0, got -5

prices = {"tea": 2.5}
try:
    print(prices["coffee"])
except KeyError as e:
    print("missing key", e)      # missing key 'coffee'

Remember

  • Read tracebacks bottom-up: exception type and message first
  • Catch specific exceptions around only the code that can fail
  • Raise exceptions with clear messages when input is invalid

Watch out for

  • Catching everything with a bare except: and hiding real bugs.

Check yourself

  1. Which is the best way to convert user text to int with a fallback of 0?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/tutorial/errors.html