Python, properly · Chapter 16 of 42

Errors and exceptions

By the end of this chapter you can catch the errors you expect, let the others through, clean up with finally whatever happens, and raise errors of your own with messages that say what went wrong. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Code that holds up
  • 4 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

Every night Rafiq, in accounts, runs a script that adds up the day's order totals. Last night it stopped at order D0005, whose total someone typed as Rs 477: int() refused it, Python printed a traceback, and none of the orders after it were counted. Rafiq does not want the script to never fail; he wants it to deal with the rows it understands, report the ones it does not, and still finish.

So far, any error you have seen ended the program. Real data is messy and real users type "two" where you asked for a number, so a program has to decide, error by error, what to do. That decision is what Python's exceptions are for.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    read_qty.py: a quantity that cannot crash

    Customers type their quantity into a WhatsApp form, and some type "two". Write a function read_qty(text) that returns the whole number in the text, and 0 when the text is not a whole number.

    read_qty("3") returns 3 and read_qty(" 12 ") returns 12 (spaces around the number are fine). read_qty("two"), read_qty("") and read_qty("2.5") return 0.

    Careful: catch only the error that bad text causes. read_qty(None) is a bug in the calling code, not bad text, and must still raise a TypeError.

  2. Task 2

    menu_errors.py: errors of your own

    Ordering a dish can fail in two ways, and the order screen wants to tell them apart. In menu_errors.py, make three exception types: OrderError, a kind of Exception; UnknownDish and DishUnavailable, both kinds of OrderError.

    Then write price_of(menu, dish_id). menu is a list of dishes like menu.json's (each a dict with id, name, price and available). It returns the dish's price; for an id no dish has, it raises UnknownDish with the message no dish called <dish_id>; for a dish that is not available, it raises DishUnavailable with the message <dish name> is not available today.

    The check uses the real menu: price_of(menu, "pizza") raises UnknownDish("no dish called pizza"), and Bombil Fry is unavailable.

  3. Task 3

    pack.py: else and finally

    Bhavna wants every packing attempt logged, even the ones that go wrong. Write pack_order(qty_text, log), where log is a list the function appends to:

    First it appends "start". Then it turns qty_text into a whole number. If that fails with a ValueError it appends "bad quantity" and returns None; if it works it appends "packed <n>" and returns n. Whatever happens, it appends "done" last.

    So pack_order("4", log) returns 4 and log is ["start", "packed 4", "done"]; pack_order("four", log) returns None and log is ["start", "bad quantity", "done"].

    Careful: pack_order(None, log) must raise the TypeError (do not catch it) and still leave log as ["start", "done"].

  4. Task 4 · interview question

    Interview: fix_handlers.py, the handler that never runs

    fix_handlers.py has a function describe(value) with three except blocks, but two of them never run: describe("seven") says something went wrong instead of not a number. Fix the order of the handlers so that:

    describe("7") returns ok 7; describe("seven") returns not a number; describe(None) returns no value; any other error, like the OverflowError from describe(float("inf")), still returns something went wrong.

    Keep the three handlers and their return values: only their order is wrong. Be ready to explain why the order matters.

What you will learn

  • What an exception is: an object Python raises, travelling up the call stack until someone catches it.
  • try and except: catching the error you expect, and only that one.
  • else and finally: code for "it worked" and for "always".
  • raise and your own exceptions: refusing bad input with a clear message and a type that callers can catch.

More in Code that holds up

Build "Errors and exceptions" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.