Lesson 20 of 30
In progress
Handle errors with try and except
Catch the errors you can recover from, let the rest through, and keep input loops from crashing on bad text.
A program that crashes on the first bad input is a demo, not a tool. Error handling is how you decide which failures are recoverable and which should stop everything loudly.
What you will learn
- Wrap risky work in
tryand catch specific exceptions. - Use
else,finallyandraisedeliberately. - Validate input in a loop instead of crashing.
Catch what you can fix
int("hello") raises ValueError. Wrapping the conversion lets you respond instead of dying.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
try:
number = int(raw)
print("Number:", number)
except ValueError:
print("That was not a whole number")
Press Run to see the output.
The try block holds only the lines that can fail. A broad try that wraps half the program hides which operation actually raised, and makes the handler guess.
Catch the specific exception you expect. except ValueError documents the failure and lets unexpected errors surface with their real traceback.
A loop that survives bad input
The practical pattern is to keep asking until the conversion succeeds. continue sends the loop back for another attempt.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
if age < 0 or age > 120:
print("Please type a realistic age.")
continue
return age
print("Recorded:", read_age())
Press Run to see the output.
Validation is split into two checks: conversion errors and range errors. Both send the learner back to the prompt without a traceback, and the function returns only a value that passed both.
input() inside the browser runner is limited, so on this page the example is illustrative; run it in a local terminal to type answers.
else and finally
else runs when the try block finished without an exception, and finally runs either way.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(parse_score("88"))
print(parse_score("eighty"))
Press Run to see the output.
Use else for code that should run only on success, so it is not accidentally protected by the try. Use finally for cleanup that must happen regardless: closing a file, releasing a lock, hiding a spinner.
Raising your own errors
Sometimes the right response is to stop. raise with a clear message turns a silent bad state into a visible failure.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
try:
print(withdraw(100, 150))
except ValueError as error:
print("Refused:", error)
Press Run to see the output.
as error binds the exception so you can print its message. Raising ValueError for a bad value is idiomatic; define your own exception class later when callers need to distinguish your errors from built-in ones.
When a program has several failure modes, a small custom exception makes them catchable without matching on message text:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFunds(f"Short by {amount – balance}")
return balance – amount
try:
withdraw(50, 80)
except InsufficientFunds as error:
print("Refused:", error)
Press Run to see the output.
The class body is deliberately empty; the name is the information. Callers can now catch InsufficientFunds without accidentally catching an unrelated ValueError from somewhere else in the same block.
Do not swallow errors
An empty except: catches everything, including KeyboardInterrupt and typos in your own code. It makes bugs invisible, which is worse than a crash.
try:
risky()
except:
pass
If you truly need a catch-all, log it and re-raise. Otherwise catch the narrow exceptions you can actually handle, and let the rest produce a traceback you can read. A useful test: if you cannot describe in one sentence why this error is safe to ignore, you should not be catching it.
A bare except: around a large block also catches NameError from a misspelled variable. The program appears to work, the feature silently does nothing, and the real bug stays hidden for days. Catch ValueError, KeyError or ZeroDivisionError specifically, and keep the try block short.
Write safe_divide(a, b) that returns the result, or None with a printed message when b is zero. Then write a loop that asks for two numbers and prints the result, recovering from both non-numeric input and division by zero.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(safe_divide(10, 2))
print(safe_divide(10, 0))
for pair in [("10", "2"), ("ten", "2"), ("10", "0")]:
try:
left = float(pair[0])
right = float(pair[1])
except ValueError:
print("Numbers only")
continue
result = safe_divide(left, right)
if result is not None:
print("Result:", result)
Press Run to see the output.
safe_divide handles its own failure and returns a value the caller can check. The loop handles conversion separately, so each error has one owner.
Recap
tryguards the risky lines;exceptnames the specific failure you can handle.elseruns on success,finallyalways runs.raisewith a clear message beats returning a silentNone; never use a bareexcept.
You have finished functions and errors. Next, you will model data with classes, so behaviour lives next to the values it changes.
Should I use try/except or check first?
Can I catch several exceptions at once?
Progress is saved in this browser only. No account, no email.