Sub topic 10
Re-raising and logging exceptions
This chapter assumes you can write try/except blocks, bind an exception with as, and use raise to throw a new exception. It also assumes you know the basics of the logging module: loggers, levels, and basicConfig.
Sometimes a handler can't fix a problem but still has something useful to do. It might record the failure, release a resource, or add context. After that, the exception should keep travelling to code that can decide what to do. This chapter covers how to do that without losing the traceback, and how to log without creating noise.
Why handle an exception and still let it continue
A handler that catches an exception ends it. Execution resumes after the try statement as if nothing happened. That is correct when you have recovered. It is wrong when you only wanted to observe the failure, because the caller now thinks the operation succeeded.
Re-raising lets a function act on a failure and still report it. Typical reasons are:
- Logging the failure close to where it happened, where you have the most context.
- Undoing partial work, such as rolling back a transaction.
- Handling only some cases of a broad exception type and passing the rest on.
The bare raise statement
A raise with no expression, used inside an except block, re-raises the exception currently being handled. The exception object keeps its original traceback, so the report still points at the line that first failed.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
def process(job):
try:
job()
except Exception:
logger.exception("job failed")
raise
def broken():
return 1 / 0
try:
process(broken)
except ZeroDivisionError:
print("caller saw the failure")Running this prints an ERROR __main__: job failed line followed by a full traceback ending in ZeroDivisionError: division by zero. Then it prints caller saw the failure. The caller still receives the original ZeroDivisionError, not a wrapper or a None.
What logger.exception does
logger.exception(message) logs at ERROR level and appends the traceback of the exception being handled. It is shorthand for logger.error(message, exc_info=True).
Three details matter:
- It only makes sense inside an
exceptblock. Elsewhere there is no active exception, and the log showsNoneType: Nonewhere the traceback should be. - Pass values as arguments, not as an f-string:
logger.exception("job %s failed", job_id). The logging module formats the message only if a handler will emit it. - For a level other than
ERROR, passexc_infoyourself:logger.warning("retrying", exc_info=True). You can also pass an exception object,exc_info=exc, which works even outside the handler.
raise versus raise exc
Inside except Exception as exc:, you could write raise exc instead of raise. In Python 3 both propagate the same object, and the original traceback entries are kept. The difference is small but real:
| Form | Effect on traceback | Notes |
|---|---|---|
| `raise` | Unchanged | Always re-raises the exception being handled. |
| `raise exc` | Adds one extra entry for the line containing `raise exc` | Works outside the handler too, but the extra entry is noise. |
Prefer the bare raise when re-raising. It shows your intent, and it can't accidentally re-raise a different object if exc was reassigned.
Re-raising conditionally
A broad handler can inspect the exception and re-raise the cases it can't deal with. This is the usual way to handle one specific error code from a general exception type.
import errno
import os
def remove_if_present(path):
try:
os.remove(path)
except OSError as exc:
if exc.errno != errno.ENOENT:
raiseA missing file is acceptable here, so that case is swallowed. Permission errors, "is a directory" errors, and everything else propagate unchanged. Note the structure: the default is to re-raise, and the handler absorbs only the case it recognizes. The reverse, absorbing everything except one case, hides unknown failures.
For simple cases a narrower except FileNotFoundError: is clearer. Conditional re-raising is for when the exception type alone can't tell the cases apart.
Cleaning up before re-raising
Another common use is undoing partial work and letting the error continue. Catching BaseException is acceptable here because you re-raise, so KeyboardInterrupt and SystemExit still propagate after the cleanup.
class Connection:
def __init__(self):
self.pending = []
def execute(self, statement):
if "DROP" in statement:
raise PermissionError("not allowed")
self.pending.append(statement)
def commit(self):
print("committed", self.pending)
self.pending.clear()
def rollback(self):
print("rolled back", self.pending)
self.pending.clear()
def run(conn, statements):
try:
for statement in statements:
conn.execute(statement)
conn.commit()
except BaseException:
conn.rollback()
raise
try:
run(Connection(), ["INSERT 1", "DROP TABLE x"])
except PermissionError as err:
print("failed:", err)The output is rolled back ['INSERT 1'] and then failed: not allowed. If the cleanup applied to the success path as well, a finally block would fit better. Here the rollback applies only to failure, so except plus raise is the right tool.
Where to log: avoid logging the same error many times
Logging and re-raising at every layer produces one failure with five log entries, each with a full traceback. This makes logs hard to read and makes error counts misleading.
A workable rule is to log an exception where you handle it, meaning where it stops propagating. Log and re-raise only when the current layer has context that no other layer has, such as a job ID or a request ID. In most programs the layers look like this:
- Low-level functions raise and do not log.
- Middle layers add context, either by chaining a new exception or by logging with that context and re-raising.
- The top level, such as a request handler, worker loop, or
main(), catches the exception, logs it once with its traceback, and decides whether to exit or continue.
Gotchas
A bare raise outside a handler
If no exception is being handled, a bare raise fails:
try:
raise
except RuntimeError as err:
print(err)This prints No active exception to reraise. The error means the raise ran when Python had no exception to re-raise. It often happens when a raise is moved out of an except block during a refactor, or into a helper function called from outside one.
An exception inside the handler replaces the current one
If the code in your handler fails, for example logger.exception itself or a rollback, that new exception propagates instead. Python attaches the original as __context__, so the traceback shows both. The re-raise on the next line never runs. When cleanup can fail, keep it simple, or guard it with its own try.
Swallowing by accident
These handlers all look like they handle a failure but leave the caller with a wrong picture:
- Logging and then returning
Noneor a default, when the caller can't tell a real result from a failure. - Logging and then continuing a loop, when later iterations depend on the failed one.
- Catching
Exceptionand forgetting theraiseat the end.
If you log an error and don't re-raise, say so in a comment, so the next reader knows the swallow is deliberate.
Summary of the decision
| Situation | What to do |
|---|---|
| You can fully recover | Handle it and continue. No re-raise. |
| You can't recover but can add information | Log with context and use bare `raise`, or chain a new exception (next chapter). |
| You need to undo partial work only on failure | `except BaseException:` cleanup, then `raise`. |
| You only recognize some cases | Handle those, `raise` otherwise. |
| You are at the program or request boundary | Log once with `logger.exception`, then exit or respond with an error. |
Exercise
A function wraps a call in try: ... except Exception as exc: logger.error(str(exc)) and returns normally afterwards. Name two problems with this handler and show the fix if the function cannot recover from the failure.
Show answer
The handler loses the traceback, because str(exc) holds only the message. It also swallows the exception, so the caller believes the call succeeded. The fix is except Exception: logger.exception("operation failed"); raise. This logs the full traceback at ERROR level and lets the original exception continue to the caller.
Exercise
What does the following code print, and why? try: try: int("x") except ValueError: print("inner") raise except ValueError as err: print("outer", type(err)._name_)
Show answer
It prints inner and then outer ValueError. The inner handler prints and then re-raises the same ValueError with a bare raise. The exception leaves the inner try and is caught by the outer except ValueError, which prints the class name.