Sub topic 10
Re-raising and Logging Exceptions
This chapter assumes you can write try/except blocks, bind an exception with as, and read a basic traceback. It covers how to record an error or clean up after it without hiding it from the caller.
Why re-raise
Sometimes a function can't fix an error but still has something useful to do with it. It might write a log entry or undo a half-finished change. If it catches the exception and stops there, the caller never learns that the operation failed. Re-raising lets you act and then pass the failure up the call stack.
Bare raise
A raise statement with no expression, inside an except block, re-raises the exception currently being handled. The original traceback is preserved.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def process(job):
try:
job()
except Exception:
logger.exception("job failed")
raise
def bad_job():
return 1 / 0
try:
process(bad_job)
except ZeroDivisionError:
print("caller saw the failure")The log shows the full traceback, and the caller still receives the ZeroDivisionError and can decide what to do.
Outside an except block, a bare raise fails with RuntimeError: No active exception to reraise.
Logging with logger.exception
logger.exception(message) logs at ERROR level and appends the traceback of the active exception. It is meant to be called from an except block. Outside one, there is no traceback to attach.
If you need a different level, pass exc_info=True:
logger.warning("retrying after failure", exc_info=True)Do not log with print(exc). That shows only the message, with no exception type, no traceback, and no timestamp, and it bypasses your logging configuration.
Cleaning up, then re-raising
Re-raising is also useful when you must undo something that only failed cases need undone. Use finally for cleanup that always runs. Use except plus raise for cleanup that runs only on failure.
def send_order(item):
raise ConnectionError("server unreachable")
def reserve(stock, item):
stock.remove(item)
try:
send_order(item)
except ConnectionError:
stock.append(item)
raise
stock = ["pen", "ink"]
try:
reserve(stock, "pen")
except ConnectionError as exc:
print(exc, stock)The item is returned to stock only when the order fails, and the caller still sees the ConnectionError.
Bare raise versus raise exc
| Statement | Effect |
|---|---|
| `raise` | Re-raises the active exception with its original traceback. |
| `raise exc` | Raises the same object, but adds the current line to the traceback. |
| `raise NewError(...) from exc` | Raises a different exception and records `exc` as its cause. |
Prefer a bare raise when you are only passing the error along. Use raise ... from when you want to change the exception type.
Log once
Each layer of a program that logs and re-raises produces another entry for the same failure. Three layers give three tracebacks, which makes the logs noisy and hard to read.
The except Exception in process is acceptable because it re-raises. Catching Exception and then swallowing the error is the pattern to avoid.
Common mistakes
- Logging inside
exceptand then returningNone. The caller treats the failure as a normal result. - Using
raise ein a function far from whereewas caught. The traceback gains a misleading extra line. - Calling
logger.error(str(exc)), which drops the traceback. Uselogger.exceptioninstead.
Exercise
A function catches OSError, calls logger.exception("save failed"), and then ends without raising. What does the caller see, and how do you fix it?
Show answer
The caller sees a normal return, usually None, so it believes the save succeeded. The traceback is in the log, but the program carries on as if nothing went wrong. Add a bare raise after the logging call so the OSError continues up the stack.