An exception signals a failure or other exceptional condition and interrupts the normal sequence of instructions.
Handle expected failures with try and except, and see why catching an error does not undo changes already made.
When an operation cannot finish, Python can raise an exception and transfer control to a handler. Follow where that transfer lands and what work has already happened. The aim is to recover from a known input problem without turning an unrelated programming bug into a plausible-looking answer.

Split a dinner bill
Four friends split ₹1,200 over UPI. Someone clears the people box, it becomes
0, and 1200 / 0 would crash the app. Wrap the risky line in try, and name
the error you expect in except:
When a line inside try raises, Python skips the rest of the try block and
jumps to the matching except. When nothing raises, the except is skipped.
The tempting shortcut is to catch everything with except Exception. Now
look what it does to a typo:
Every split comes out as 0.0. Narrow the except so the real bug shows, then fix it.
A crash you can see beats a wrong answer you can't. Catch the case you expect (zero people) and let real bugs fail loudly while you test.
The type name tells you what went wrong. These are the ones you'll meet most:
1200 / 0 # ZeroDivisionError: division by zero
int("four") # ValueError: the type is right, the content is wrong
"Total: " + 450 # TypeError: str and int can't be added
[120, 80][5] # IndexError: list index out of range
{"tea": 15}["coffee"] # KeyError: 'coffee'
totl # NameError: name 'totl' is not defined (a typo)
"upi".uppercase() # AttributeError: str has no 'uppercase'A bare
except:also catchesKeyboardInterruptandSystemExit. For these recovery examples, name the expected exception so an interruption or exit request is not accidentally swallowed.
Preparing this topic’s interactive investigation…
Handling an error does not undo earlier work
A handler does not resume the failing line. It runs after control has left
the failed try suite, possibly unwinding several function calls. Nor does
it roll back assignments or list changes that already happened:
If a row must be accepted as a whole, compute and validate its fields in
local variables, then append the finished row. Do not append half a row
and hope except will remove it. If one bad row should leave the rest
processable, put the recovery boundary inside the loop, as below.
A fallback is also a policy. Returning 0.0 for a zero-person split makes
the exercise UI continue, but merges “invalid split” with “valid zero bill.”
For a caller that must distinguish them, return a separate status or raise
an exception it can handle. Catching an error is useful only when the
handler knows how to proceed correctly.
Read an amount from a form
A payment form sends whatever was typed: "450", "₹450", " 99.5 ", or
None when the box was left empty. Bad text raises ValueError; None
raises TypeError. Catch both in one except with a tuple, and use as e to
read the message:
float forgives spaces around a number, but not a ₹ sign. Now a whole list of
prices comes in. Where the try sits decides how much one bad value costs you:
prices = ["120", "80", "free", "60"]
total = 0
try:
for p in prices:
total += float(p)
except ValueError:
print("bad price", end=" ")
print(total)Move it inside, and each row succeeds or fails on its own:
Book a train ticket
So far Python raised the errors. Your own functions can raise them too, when an
input breaks your rules. Give the failure a name of its own by making a class
that inherits from Exception. pass means "nothing to add":
raise stops the function at once and hands the error to whoever called it.
The caller can now tell "train is full" apart from "bad input" and treat each
one differently. The mistake people really make is forgetting the word raise:
Four seats were sold when only two were left (see the -2). Make the check actually stop the booking.
Booking has two more steps. The "ticket booked" SMS should go out only if
payment worked, and the payment page must close whatever happens. That is
what else and finally are for:
finally runs even when the try has already decided to return:
Now predict a version that prints from inside finally:
def f():
try:
return "from try"
finally:
print("cleanup, then", end=" ")
print(f())Traps and habits
withdoes thefinallyfor you.with open("bill.txt") as f:closes the file even if the body raises. Use it for files and connections.- Try first, then handle. Python style prefers
try: price = menu[item]withexcept KeyErrorover checkingif item in menufirst. Both work; thetryversion avoids a separate membership check, but does not by itself make a multi-step concurrent operation atomic. - Log, then pass it on. A bare
raiseinside anexceptre-raises the same error.raise BookingError("bad input") from eswaps in your own error but keeps the original as its cause. - Group your errors.
class SeatsFullError(BookingError)makes it a kind ofBookingError, soexcept BookingErrorcatches both. Built-ins work the same way:except LookupErrorcatchesKeyErrorandIndexError. - Never
returninsidefinally. It silently throws away any error thetryraised. - Syntax errors in the current file prevent its handlers from running.
A running program can catch
SyntaxErrorfrom an operation that compiles other source, such ascompile(...)or importing a malformed module.
Read a traceback from its final exception line back through the calls. The innermost frame identifies the failed operation; outer frames explain how its inputs arrived. Fix a wrong argument upstream instead of adding a broad handler around the symptom.
For transfer, process quantity strings "2", "bad", "0", "3". Return
accepted quantities and error positions. Decide whether zero is valid
separately from whether int can parse it. Show that the last 3 survives
and that a rejected row never changes the accepted total. Then explain
which failures you intentionally allow to propagate.
Quick practice
try:
print(100 / 0)
except Exception:
print("something broke")
except ZeroDivisionError:
print("no people")try:
count = int("7")
except ValueError:
print("bad", end=" ")
else:
print("ok", end=" ")
finally:
print("done")print("Total: " + 450)KeyErrorAsking for a dish that isn't on the menu crashes. Catch the right error.
🎯 Your turn
Write safe_split(total, people). It returns each person's share rounded to two
decimals, or 0.0 when people is 0. The zero-person case does not raise for the numeric inputs used here.
safe_split(100, 4)→25.0safe_split(100, 0)→0.0
Hint: put round(total / people, 2) in a try: and return 0.0 from
except ZeroDivisionError:.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a warm-up to a batch of orders where any row can be broken.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write safe_div(a, b) returning a / b, or 0.0 if b is zero.
Write to_float(text) returning float(text), or None if it's not a valid number OR is None. Catch both errors in one except.
Write safe_divide_all(pairs) where each pair is [a, b]. Return a list of a / b, using None for any pair that divides by zero.
Write parse_settings(lines) for "key=value" lines. Return {"settings": {...}, "errors": [...]}: values that look like whole numbers become int, others stay strings, and any line without = goes into errors (kept as-is).
Each row is {"price": <str>, "qty": <str>}. Write safe_batch(rows) returning {"totals": [...], "errors": [...]} — round(price*qty, 2) per good row (price→float, qty→int), and the index of any row that fails.