Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Exceptions & Errors

Exceptions 20 minAn exception signals a failure or other exceptional condition and interrupts the normal sequence of instructions.

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.

Three stacked function boxes: float("12%") at the bottom raises ValueError, the error climbs past checkout(), which has no try, and is caught by the except ValueError in pay_screen() at the top. A side note says that with no except anywhere the app stops with a traceback

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:

python

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:

broken — fix it

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 catches KeyboardInterrupt and SystemExit. 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:

python

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:

python

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:

What does this print?
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:

python

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":

python

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:

broken — fix it

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:

python

finally runs even when the try has already decided to return:

step through it
1def f():
2 try:
3 return "from try"
4 finally:
5 print("cleanup")
6 
7result = f()
8print(result)

Now predict a version that prints from inside finally:

What does this print?
def f():
    try:
        return "from try"
    finally:
        print("cleanup, then", end=" ")

print(f())

Traps and habits

  • with does the finally for 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] with except KeyError over checking if item in menu first. Both work; the try version avoids a separate membership check, but does not by itself make a multi-step concurrent operation atomic.
  • Log, then pass it on. A bare raise inside an except re-raises the same error. raise BookingError("bad input") from e swaps in your own error but keeps the original as its cause.
  • Group your errors. class SeatsFullError(BookingError) makes it a kind of BookingError, so except BookingError catches both. Built-ins work the same way: except LookupError catches KeyError and IndexError.
  • Never return inside finally. It silently throws away any error the try raised.
  • Syntax errors in the current file prevent its handlers from running. A running program can catch SyntaxError from an operation that compiles other source, such as compile(...) 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

What does this print?
try:
    print(100 / 0)
except Exception:
    print("something broke")
except ZeroDivisionError:
    print("no people")
What does this print?
try:
    count = int("7")
except ValueError:
    print("bad", end=" ")
else:
    print("ok", end=" ")
finally:
    print("done")
What happens when this runs?
print("Total: " + 450)
broken — fix itKeyError

Asking 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.0
  • safe_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.

Your task
Build safe_split(total, people). It returns each person's share, or 0.0 if people is 0 (it never crashes). Example: safe_split(100, 4) → 25.0.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upSafe divide

Write safe_div(a, b) returning a / b, or 0.0 if b is zero.

try/except
DrillTolerant float parse

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.

tuple-exceptcast
BuildDivide a batch

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.

looptry/exceptlist
BossParse config lines

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).

loopsplitcastdictguard
CapstoneSafe order batch

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.

loopenumeratecasttuple-exceptdict
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — safe_split(): Splits the total between people without ever crashing.
Scenario Someone clears the 'people' field to 0 mid-edit. Dividing by 0 would crash the app — this stays calm and returns 0.0.
safe_split.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
safe_split(total, people) → floatPer-person share, or 0.0 if people is 0.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.