Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

Exceptions: expecting the unexpected

By the end of this chapter, you'll be able to

  • Read a Python error message (traceback) to find its cause
  • Catch an error with try and except
  • Use else and finally to separate the cases
  • Raise your own errors with raise to refuse invalid data

What is an exception?

When Python runs into a situation it can't handle, it creates an exception: an object that describes the problem. If nobody deals with it, the program stops and shows a traceback, that is, the path followed up to the error, then its type and its message.

price = int("ten")

The traceback ends with ValueError: invalid literal for int() with base 10: 'ten'. Read it from the end: the type (ValueError, an incorrect value) and the message tell you exactly what to fix. The lines above show where the error happened.

Some exceptions you'll often meet:

  • ValueError: the value doesn't have the right form (int("ten"));
  • TypeError: the type isn't suitable ("10" / 2);
  • ZeroDivisionError: division by zero;
  • KeyError and IndexError: a dictionary key or list index that doesn't exist;
  • FileNotFoundError: the file doesn't exist (we'll see it in the next chapter).

Catching an error with try and except

You put the code that may fail in a try block. If an exception of the given type happens, Python jumps straight to the matching except block instead of stopping.

def read_age(text):
    try:
        age = int(text)
    except ValueError:
        return None
    return age

for entry in ["17", "seventeen", " 42 "]:
    print(repr(entry), "→", read_age(entry))
'17' → 17
'seventeen' → None
' 42 ' → 42

repr(entry) displays the text with its quotes: handy for seeing spaces. By the way, int(" 42 ") ignores the spaces around the number.

The except block returns None. The program carries on normally, with no traceback.

Step 5 of 5
Text description of the animation
  1. We call read_age("seventeen").
  2. We enter the try block: Python watches what happens inside.
  3. int can't convert this text: a ValueError is raised. The variable age is never created.
  4. Python looks for an except that matches the type of the error: except ValueError fits.
  5. The except block returns None. The program carries on normally, with no traceback.

Several excepts, then else and finally

A single try can have several except blocks, one per type of error. Two optional blocks complete the picture:

  • else runs only if no error happened;
  • finally runs in every case, error or not. It's used for tidying up: closing a connection, showing a summary.
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Can't divide by zero")
    except TypeError as error:
        print("Incompatible types:", error)
    else:
        print("Result:", result)
    finally:
        print("Calculation done")

divide(10, 4)
divide(10, 0)
divide("10", 2)
Result: 2.5
Calculation done
Can't divide by zero
Calculation done
Incompatible types: unsupported operand type(s) for /: 'str' and 'int'
Calculation done

except TypeError as error gives a name to the caught exception: error holds its message, which you can display or log.

Raising your own errors with raise

A function that receives absurd data mustn't "pretend". It raises an exception with raise, and it's the caller who decides what to do with it:

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError(f"invalid amount: {amount}")
    if amount > balance:
        raise ValueError(f"insufficient balance ({balance} available)")
    return balance - amount

balance = 50
for amount in [20, -5, 100]:
    try:
        balance = withdraw(balance, amount)
        print("Withdrew", amount, "→ balance", balance)
    except ValueError as error:
        print("Refused:", error)
Withdrew 20 → balance 30
Refused: invalid amount: -5
Refused: insufficient balance (30 available)

Why not simply return -1 or None when something's wrong? Because a special value is easy to forget: the caller may use it as a real balance. An exception doesn't go unnoticed: if nobody catches it, the program stops with a clear message instead of carrying on with wrong data.

Your turn

Worked exercise

Worked exercise: the length of a playlist

Write a function to_seconds(duration) that converts a text "mm:ss" into a number of seconds ("3:45" gives 225). It raises a ValueError with a clear message if the format is wrong ("two minutes") or if the seconds aren't between 0 and 59 ("2:75"). Then compute the total length of the playlist ["3:45", "4:10", "2:75", "two minutes", "5:02"], ignoring invalid durations, with a message for each.

Hint 1
duration.split(":") returns a list. If it doesn't contain exactly two pieces, the format is wrong.
Hint 2
int("two") already raises a ValueError on its own: no need to check it yourself. Your try around the call will catch both cases.
Show the solution and common mistakes
def to_seconds(duration):
    pieces = duration.strip().split(":")
    if len(pieces) != 2:
        raise ValueError(f"expected format mm:ss, got {duration!r}")
    minutes, seconds = int(pieces[0]), int(pieces[1])
    if minutes < 0 or not 0 <= seconds < 60:
        raise ValueError(f"impossible duration: {duration!r}")
    return minutes * 60 + seconds

playlist = ["3:45", "4:10", "2:75", "two minutes", "5:02"]
total = 0
for duration in playlist:
    try:
        total += to_seconds(duration)
    except ValueError as error:
        print("Skipped:", error)
print(f"Total length: {total // 60} min {total % 60} s")
Skipped: impossible duration: '2:75'
Skipped: expected format mm:ss, got 'two minutes'
Total length: 12 min 57 s

{duration!r} in an f-string displays the value like repr, with its quotes.

Common mistakes:

  • Putting the whole for loop inside a single try: at the first invalid duration, the loop stops and the following durations are never counted.
  • Returning 0 for an invalid duration instead of raising an error: the total would be wrong without anyone noticing.

Summary

  1. 1A traceback is read from the end: the exception's type and message give the cause.
  2. 2try holds the risky code, except handles one precise type of error.
  3. 3else runs if there was no error, finally always runs.
  4. 4raise ValueError("…") refuses invalid data in a way that can't be ignored.
  5. 5Never catch every error: you'd hide your own bugs.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.