Sikau

Python · Day 7 · about 35 min

Errors and exceptions

try, except, else, finally — and raising your own.

Things go wrong

A customer types "free" in the price box. A file is missing. The shop runs out of momo. Programs meet bad input and broken situations all the time, and Python's answer is the exception: an object that's *raised* where the problem happens and travels up through the calling functions until something *catches* it — or, if nothing does, the program stops and prints a traceback.

Python style leans on exceptions more than many languages. The motto is "easier to ask forgiveness than permission" (EAFP): just try the conversion and handle the ValueError, instead of first checking every character of the text.

Reading a traceback

Read a traceback from the bottom up. The last line names the exception type and its message, like ZeroDivisionError: division by zero. The lines above list the calls that led there, oldest first, each with a file name, line number and the source line — the deepest call, where it actually broke, is just above the message.

def share(total, people):
    return total / people

def bill():
    return share(500, 0)

bill()
  • ValueError — right type, bad value: int("free").
  • TypeError — wrong type: "5" + 3, or the wrong number of arguments.
  • KeyError, IndexError — a missing key or position.
  • AttributeError — no such attribute or method, often on None.
  • ZeroDivisionError, FileNotFoundError, NameError…

The rest of this lesson

  • try, except, else, finallyexplain
  • Which blocks run?predict
  • Name that exceptionmatch
  • Where the exception goesorder
  • A shop that fails politelywrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Python