Bigger programs · lesson 6 of 12
Parts in this lesson
ATracebackwhere it went wrong
Btry: except:catch an error
Celse: finally:no error, and always
Draiseraise an error yourself
Eas errthe error itself

When things go wrong

Last updated

Until now, an error has stopped the program. In this lesson you'll read a traceback that runs through several functions, catch an error with try and except so the program carries on, tidy up with else and finally, raise errors of your own, and see why you should catch only the error you expect.

By the end of this lesson you can

  • Read a traceback from the bottom up, through several function calls
  • Catch an error with try and except, and use else and finally
  • Raise an error with raise when a function is given a value it can't use
  • Catch only the errors you expect, so real mistakes still show

Reading a traceback

When an error happens inside a function, the message is a traceback: the trail of calls that led to it. Press Run and read it.

Step 1 code main.py
Edit the code, then run it again

Read it from the bottom up. The last line says what went wrong: > can't compare text with a number. The line above says where: line 2, inside fine_for. Above that, each File line is one step further back: fine_for was called from line 10 in total, which was called from line 14.

The bottom tells you where Python noticed the problem; the cause is often further up. Here it's on line 14: "4" is text, so days was text when it reached line 2. Change it to 4 and the program prints 175.

try and except

Put lines that might fail in a try block. If one of them raises an error, Python skips the rest of the block and jumps to an except that names that kind of error. Then the program carries on after it, instead of stopping.

Watch it run with ten in the input box. Line 3 raises ValueError, so line 4 never runs, and the except on line 5 catches it. Then change the input to 4 and watch again: with no error, the except block is skipped.

Step 2 code main.py
Edit the code, then run it again

Keep the try block small: only the lines that can fail, and the ones that depend on them. That way you know which line the except is for.

else and finally

A try can have two more parts. The else block runs only if no error was raised; it's the place for the lines that need the try to have worked. The finally block runs every time, error or not; it's for tidying up, like closing a file.

Step 3 code main.py
Edit the code, then run it again

Watch it run for "Matilda": line 6 raises KeyError, the except catches it, else is skipped, and finally still runs. Why not put line 10 inside the try? Because then a mistake on line 10 could be caught by an except that was only meant for line 6.

Raising your own errors

Your own functions can raise errors too. A fine for a negative number of days makes no sense, so fine_for refuses with raise, naming the kind of error and a message. ValueError is the usual choice when a value has the right type but a wrong value.

except ValueError as err gives the caught error the name err, so line 11 can print its message.

Step 4 code main.py
Edit the code, then run it again

Raising is better than quietly giving back a made-up answer like 0. The caller finds out at once that something is wrong, and can decide what to do about it.

Catch only what you expect

This program looks up a book that isn't in the stock dictionary, and tries to catch the problem. Press Run:

Step 5 code main.py
Edit the code, then run it again

The except was never used. A missing key raises KeyError, not ValueError, and an except catches only the kind it names. Change line 5 to except KeyError: and run it again.

The opposite mistake is worse. except Exception: catches nearly every error, including your own typos. This program means to print 2. Press Run:

Step 5 code main.py
Edit the code, then run it again

Name the errors you expect and know how to handle. Let the rest stop the program, with a traceback that points at the real problem.

Check what you learned

Four questions. Pick or type an answer, then check it.

What does this program print?
try:
    n = int("7")
except ValueError:
    print("bad")
else:
    print(n * 2)
finally:
    print("done")
Which part of a traceback says what went wrong?
stock[title] fails because the key isn't there. Which except catches it?
fine_for(-2) is called, but negative days make no sense. What should fine_for do?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python