Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Into the real world
EXPERIMENT 18 / 101

When things go sideways.

Handle an expected failure without hiding the useful evidence.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

An exception interrupts the normal flow when an operation fails. Use try and except to handle failures you expect and know how to recover from. Catch specific exception types so unrelated programming mistakes remain visible.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

exceptions.py
raw_minutes = "later"

try:
    minutes = int(raw_minutes)
except ValueError:
    print("Please enter a whole number.")
else:
    print(f"Scheduled for {minutes} minutes")
↳ EXPECTED OUTPUT
Please enter a whole number.

03 Under the hood

  1. 1

    int() cannot interpret "later" as an integer, so it raises ValueError. The except block provides a helpful response.

  2. 2

    else runs only if the try block finishes without an exception. finally, when present, runs as the statement exits, whether it succeeded or failed.

  3. 3

    Keep the try block narrow. It should be obvious which operation is expected to fail. Use raise ValueError(...) when your own function receives an invalid value it cannot reasonably use.

04 Your turn, builder

A SMALL MISSION

Convert "12.5" using float(), catch ValueError, and print the converted number when conversion succeeds.

Reveal one possible solution +
one_possible_solution.py
try:
    value = float("12.5")
except ValueError:
    print("Not a number")
else:
    print(value)

05 Check your signal

QUICK SIGNAL CHECK

When does the else block of try/except run?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.