Python 3D Academyবাংলা

Chaining errors with raise from, and logging what happened

🌍 In real life. A courier app that only says "Delivery failed" leaves you guessing. "Delivery failed, because: the house number wasn't found" tells you exactly what to fix. And a night-shift guard keeps a log book: 10:05 pm, gate locked; 2:40 am, alarm on floor 3. In the morning, nobody has to guess what happened.

Programs need both: errors that carry their cause along, and a written record of what the program did.

The idea in one sentence: raise NewError(...) from err raises a clearer error and keeps the original one as its cause, and the logging module records what a program does, with a level on every message, instead of scattering print calls.

Its words:

  • exception chaining: linking a new error to the error that caused it
  • __cause__: the attribute where the new error keeps the old one
  • log level: how serious a message is: DEBUG < INFO < WARNING < ERROR < CRITICAL
  • logging.basicConfig(...): sets up logging once: which level to show, and how each line looks

Step by step, a clearer error:

  1. Deep inside, int("ten") raises ValueError: invalid literal for int() with base 10: 'ten'. True, but it doesn't say which number was wrong.
  2. The function that knows what it was reading catches it: except ValueError as err:.
  3. It raises an error that makes sense to the caller, from the original: raise RuntimeError("age must be a number") from err.
  4. The new error's __cause__ is the ValueError, so nothing is lost.
def read_age(text):
    try:
        return int(text)
    except ValueError as err:
        raise RuntimeError(f"age must be a number, not {text!r}") from err

try:
    read_age("ten")
except RuntimeError as e:
    print(e)
    print("because:", e.__cause__)
On your own computer, a full traceback shows both errors, joined by the line: The above exception was the direct cause of the following exception. This app shows the last line only.

Hiding a cause on purpose. Sometimes the old error adds nothing for the reader. raise NewError(...) from None raises the new error with no cause shown. Use it sparingly: a hidden cause is a clue thrown away.

Logging: a record, not output. print is for what the program shows its user. A log is the program's diary, for you: every message has a level, and one line of set-up decides which levels appear, how they look, and where they go. Turning the details off later means changing that one line, not hunting down forty prints.

import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logging.debug("this detail is hidden")
logging.info("shop opened")
logging.warning("only 3 cups of tea left")
logging.error("card payment failed")
Log messages go to stderr, the error stream, which this page shows in red. level=logging.INFO hides the DEBUG line; change it to logging.DEBUG and it appears.

On a real computer. Add the time with format="%(asctime)s %(levelname)s: %(message)s", and keep the log in a file with filename="shop.log". Inside an except block, logging.exception("payment failed") writes the message and the whole traceback, which is exactly what you want to find in the morning.

Why both help. A chained error answers "what went wrong, and why" at the moment it happens. A log answers "what was the program doing before that". Together they turn a mystery into a story.

Mistakes and edge cases.

  • Raising a new error without from. Inside except, a plain raise RuntimeError(...) still shows both errors, but joined by During handling of the above exception, another exception occurred, which reads like a second bug. from err says it was on purpose.
  • from with something that isn't an error. raise RuntimeError("bad") from text gives TypeError: exception causes must derive from BaseException. Put the caught error after from.
  • Swallowing errors. except ValueError: pass throws the clue away. If you really carry on, at least logging.warning(...) what happened.
  • Logging before basicConfig. The first logging call sets logging up with the defaults (WARNING and up), and a later basicConfig then changes nothing. Call basicConfig once, at the start.
  • Expecting INFO by default. With no set-up, only WARNING, ERROR and CRITICAL appear; logging.info(...) is silently skipped.

Quiz

  1. What does this print?

    try:
        try:
            1 / 0
        except ZeroDivisionError as err:
            raise ValueError("bad split") from err
    except ValueError as e:
        print(e, "|", type(e.__cause__).__name__)
  2. After logging.basicConfig(level=logging.WARNING), which messages appear?

    • WARNING, ERROR and CRITICAL
    • Only WARNING
    • Every level, DEBUG included
  3. What does raise ValueError("bad input") from None do?

    • Raises the ValueError without showing an earlier error as its cause
    • Raises nothing at all
    • Raises a ValueError whose message is None
  4. load_price("abc") should raise RuntimeError with the ValueError as its cause, but raises TypeError: exception causes must derive from BaseException. Which line is wrong?

    def load_price(text):
        try:
            return float(text)
        except ValueError as err:
            raise RuntimeError("price must be a number") from text
  5. A shop's program should record "card payment failed" for the owner. Why logging.error instead of print?

    • A log line has a level, can go to a file with the time, and can be filtered by one line of set-up
    • logging runs faster than print
    • print can't show text about errors

Coding tasks

  1. Change parse_price so that a bad price raises PriceError(f"not a price: {text}") from the original ValueError. The code at the bottom should then print not a price: abc | cause: ValueError.

  2. Replace the print in check_stock with logging: always an INFO message cups left: N, and also a WARNING running low! when fewer than 5 cups are left. (This task sends the log to stdout so the checker can read it.)