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:
- Deep inside,
int("ten")raisesValueError: invalid literal for int() with base 10: 'ten'. True, but it doesn't say which number was wrong. - The function that knows what it was reading catches it:
except ValueError as err:. - It raises an error that makes sense to the caller, from the original:
raise RuntimeError("age must be a number") from err. - The new error's
__cause__is theValueError, 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__)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")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 plainraise RuntimeError(...)still shows both errors, but joined by During handling of the above exception, another exception occurred, which reads like a second bug.from errsays it was on purpose. - from with something that isn't an error.
raise RuntimeError("bad") from textgivesTypeError: exception causes must derive from BaseException. Put the caught error afterfrom. - Swallowing errors.
except ValueError: passthrows the clue away. If you really carry on, at leastlogging.warning(...)what happened. - Logging before basicConfig. The first logging call sets logging up with the defaults (WARNING and up), and a later
basicConfigthen changes nothing. CallbasicConfigonce, at the start. - Expecting INFO by default. With no set-up, only WARNING, ERROR and CRITICAL appear;
logging.info(...)is silently skipped.
Quiz
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__)After logging.basicConfig(level=logging.WARNING), which messages appear?
- WARNING, ERROR and CRITICAL
- Only WARNING
- Every level, DEBUG included
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
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 textA 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
Change
parse_priceso that a bad price raisesPriceError(f"not a price: {text}")from the originalValueError. The code at the bottom should then printnot a price: abc | cause: ValueError.Replace the
printincheck_stockwith logging: always an INFO messagecups left: N, and also a WARNINGrunning low!when fewer than 5 cups are left. (This task sends the log to stdout so the checker can read it.)