Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

try / except / finally & raise

15 min 30 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 2 of 5 · View course roadmap
Step 1

Learn the idea

Exception handling lets your program survive failures instead of crashing:

  • try: — the risky code
  • except ValueError: — runs only if that error occurred (always catch specific exceptions)
  • else: — runs if no error happened
  • finally: — always runs (cleanup: closing files, connections)
  • raise ValueError("message") — throw your own errors when input is invalid

Never write a bare except: that silently swallows everything — it hides real bugs. Catch what you expect, let the rest crash loudly.

Where you'll use this

Production services wrap every network call, file read and JSON parse in try/except — a payment API that crashes on one malformed record instead of logging and continuing loses real money.

Common mistakes

  • Bare except: swallowing everything including typo-NameErrors and Ctrl-C — always name the exception you expect.
  • Wrapping 50 lines in one try — narrow the try block to the single risky call so you know what failed.
  • Using exceptions for normal flow control when an if would do: check if key in d rather than catching KeyError you expect half the time.

Pro tip

except ValueError as e: print(f"bad input: {e}") — binding the exception gives you its message for logs. Multiple types in one clause: except (ValueError, KeyError):.

Step 2

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +30 XP

Blank · autosaved

Write to_number(text) that returns int(text), but returns -1 if conversion raises ValueError. Print to_number("42") and to_number("oops").

Target output
42
-1
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. When does finally run?
2. Why is a bare except: bad practice?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path