try / except / finally & raise
Lesson 2 of 5 · View course roadmap
Learn the idea
Exception handling lets your program survive failures instead of crashing:
try:— the risky codeexcept ValueError:— runs only if that error occurred (always catch specific exceptions)else:— runs if no error happenedfinally:— 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 drather 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):.
Try it yourself
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”.
Output appears here…
Pass the challenge +30 XP
Write to_number(text) that returns int(text), but returns -1 if conversion raises ValueError. Print to_number("42") and to_number("oops").
42 -1
try: return int(text) / except ValueError: return -1
def to_number(text):
try:
return int(text)
except ValueError:
return -1
print(to_number("42"))
print(to_number("oops"))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.