Python Errors and Exceptions · Lesson 95 of 149

Python try and except

What you will learn

  • What an exception is and why programs crash without handling
  • Writing try and except
  • Catching specific error types, and several at once
  • Using the error object (as e)
  • How an error travels up through function calls
  • Why bare except is a bad habit

1. Errors stop the program

When Python cannot do something, it raises an exception, and if nothing handles it, the program stops with an error message:

n = int("abc")
print("never reached")
ValueError: invalid literal for int() with base 10: 'abc'

The second line never runs. Real programs meet bad input all the time: a user types text instead of a number, a file is missing, a network drops. You do not want a crash each time. Exception handling lets you catch the problem and decide what to do.

2. try and except

Put the risky code in a try block, and the recovery code in an except block:

try:
    n = int("abc")
except ValueError:
    print("not a number")
not a number

How it works:

  1. Python runs the try block line by line.
  2. If no error happens, the except block is skipped.
  3. If a ValueError happens, Python jumps out of the try block at once (the rest of it is skipped) into the except block.
  4. After that, the program continues normally below.

Here it is inside a function, which returns None when the conversion fails:

def to_int(t):
    try:
        return int(t)
    except ValueError:
        return None

print(to_int("42"), to_int("x"), to_int(""), to_int(" 7 "))
42 None None 7

Note that int(" 7 ") works because int ignores spaces around the digits.

Quick check: what prints?
try:
    print("a")
    1 / 0
    print("b")
except ZeroDivisionError:
    print("c")
print("d")

a, c, d. The line print("b") is skipped because the error jumped to the except block.

3. Catch specific types

After except, name the type of error you expect. Only that type (and its sub-types) is caught:

def f(x):
    try:
        return 10 / x
    except ZeroDivisionError:
        return "zero"
    except TypeError:
        return "type"

print(f(2), f(0), f("a"))
5.0 zero type
  • You can have several except blocks; Python uses the first one that matches.
  • To handle different types the same way, group them in a tuple:
try:
    int(None)
except (ValueError, TypeError) as e:
    print(type(e).__name__, e)
TypeError int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
  • An error that no block matches is not caught and keeps going up (section 5).

Catch only what you expect and know how to handle. An except that is too wide can hide real bugs.

4. The error object

Add as name to get the exception object itself:

try:
    int("abc")
except ValueError as e:
    print(type(e).__name__)
    print(e)
    print(e.args)
    print(repr(e))
ValueError
invalid literal for int() with base 10: 'abc'
("invalid literal for int() with base 10: 'abc'",)
ValueError("invalid literal for int() with base 10: 'abc'")
  • print(e) shows the message.
  • e.args is a tuple of the arguments given when it was raised.
  • type(e).__name__ is the error's class name.

A few common ones and their messages:

try:
    1 / 0
except ZeroDivisionError as e:
    print(e)

try:
    [1][5]
except IndexError as e:
    print(e)

try:
    {"a": 1}["b"]
except KeyError as e:
    print(e, repr(e))

try:
    print(undefined)
except NameError as e:
    print(e)
division by zero
list index out of range
'b' KeyError('b')
name 'undefined' is not defined

The name e exists only inside the except block. Python deletes it afterwards, so using e later gives a NameError. Copy it to another name if you need it later.

5. Errors travel up

If a function does not handle an error, it passes to the caller, then the caller's caller, and so on, until something catches it (or the program stops):

def risky():
    return 1 / 0

def mid():
    return risky()

try:
    mid()
except ZeroDivisionError:
    print("propagated through two calls")
propagated through two calls

You can therefore handle errors at the level that knows what to do. A low-level function just lets the error pass; the code at the top, which can show a message to the user or retry, catches it. Nested try blocks work too: an inner try that does not match passes the error to the outer one.

6. Do not use a bare except

try:
    ...
except:            # catches EVERYTHING
    pass

A bare except: catches every kind of error, even a typing mistake in your code (NameError) or the user pressing Ctrl+C (KeyboardInterrupt). With pass, the problem disappears silently, which makes bugs very hard to find.

Better choices:

  • catch the specific error you expect;
  • if you must catch "anything unexpected" (for example at the top of a program, to log it), use except Exception, which leaves out KeyboardInterrupt and SystemExit.

Exception is the base class for the ordinary errors. The classes form a family tree:

print(issubclass(KeyboardInterrupt, Exception))
print(issubclass(KeyError, LookupError), issubclass(ZeroDivisionError, ArithmeticError))
print(issubclass(Exception, BaseException))
False
True True
True

KeyError and IndexError are both kinds of LookupError; catching LookupError catches both. Order matters: put the more specific except first, because a broad class listed first would catch everything and the specific one would never run.

try:
    {}["x"]
except LookupError:
    print("LookupError first")
except KeyError:
    print("never")
LookupError first

7. Look before you leap, or ask forgiveness?

There are two styles:

Style Example
LBYL (look before you leap) if key in d: v = d[key]
EAFP (easier to ask forgiveness than permission) try: v = d[key] / except KeyError: ...

Python programmers like EAFP when failure is rare or when checking first is awkward (is this text a valid number? the easiest test is to try int). Use a plain if when the check is simple and failure is common (dict.get, lesson 9.2).

Worked example: asking for a valid age

Keep asking until the user gives a whole number from 0 to 120. The answers are scripted here, so the example is repeatable.

answers = iter(["abc", "-3", "200", " 12 "])


def read_age():
    while True:
        raw = next(answers)
        try:
            age = int(raw)
            if not 0 <= age <= 120:
                raise ValueError("age must be between 0 and 120")
            return age
        except ValueError as e:
            print(f"Try again ({raw!r}): {e}")


print("Age:", read_age())
Try again ('abc'): invalid literal for int() with base 10: 'abc'
Try again ('-3'): age must be between 0 and 120
Try again ('200'): age must be between 0 and 120
Age: 12
Step What it shows
int(raw) inside try the risky call is the only thing that can raise ValueError for bad text
raise ValueError(...) our own rule uses the same error type, handled in one place (lesson 14.4)
except ValueError as e one handler for both problems, with the message shown
while True and return the loop repeats until a good value is returned

In a real program, replace next(answers) with input("Age: "). The answers are made up.

Common mistakes

  • Bare except: or except Exception: pass that hides errors.
  • Putting too much code in try. Keep it small, so you know which line failed.
  • Catching too early, when the caller is the one who can decide what to do.
  • Listing a broad class before a narrow one.
  • Using e after the except block.
  • Forgetting that a statement after the error in try never runs.
  • Using try to hide a bug that should be fixed (such as a misspelled name).

Key takeaways

  • An exception stops the program unless it is caught.
  • try holds the risky code; except Type handles that type; the rest of try is skipped when an error occurs.
  • Several except blocks are checked in order; use a tuple to share a handler; as e gives the error object.
  • Uncaught errors travel up to the callers, so handle them where you know what to do.
  • Catch specific types; avoid bare except.

Practice

1. What happens to the rest of a try block after an error occurs?

Show answer

It is skipped. Python jumps straight to the matching except block.

2. Write code that returns 0 when int(text) fails.

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

3. How do you handle both ValueError and TypeError with the same code?

Show answer

except (ValueError, TypeError):

4. Why is except: followed by pass dangerous?

Show answer

It catches every error, including typing mistakes in your code and Ctrl+C, and hides them, so bugs become invisible.

5. {}["x"] raises KeyError. Which of these catches it: LookupError, ValueError, Exception?

Show answer

LookupError (its parent) and Exception do; ValueError does not.

6. What is wrong with print(e) placed after the except block?

Show answer

Python deletes e when the block ends, so you get a NameError. Copy it to another name inside the block if you need it later.