Recipe 5.2 · Python
throw; Versus throw ex;
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Code catches an exception, does some cleanup or logging, and rethrows it with throw ex;. The
stack trace now starts at the rethrow, not at the line that failed. You see that SaveOrder
threw, but not that the real failure was three calls deeper, in a currency conversion.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Rolling back a transaction and re-throwing in a way that loses context
Source: ImproveCode, Chapter 5, Recipe 5.2 "`throw;` Versus `throw ex;`"
Section: The way it's often written
Book page: 103 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
pyodbc replaces SqlConnection/SqlTransaction (autocommit off = transaction). Python's
`raise ex` keeps the traceback, so the C# `throw ex` loss is mimicked with
ex.with_traceback(None) -- the original stack trace is discarded.
"""
from __future__ import annotations
from typing import Any
import pyodbc
class OrderRepository:
def __init__(self, conn: pyodbc.Connection) -> None:
self.conn = conn
def save_order(self, order: Any) -> None:
self.conn.autocommit = False # BeginTransaction
try:
self.insert_header(order)
self.insert_lines(order)
self.conn.commit()
except Exception as ex:
self.conn.rollback()
raise ex.with_traceback(None) from None # like C# "throw ex"
def insert_header(self, order: Any) -> None: ...
def insert_lines(self, order: Any) -> None: ...
The improved recipe
Use throw; to rethrow the same exception. When you want to add context, throw a new exception
and pass the original as the inner exception.
Requirements: Python 3.12+. Install: pip install aioodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Transaction runner that rethrows correctly, and wrapping errors with context
Source: ImproveCode, Chapter 5, Recipe 5.2 "`throw;` Versus `throw ex;`"
Section: The improved recipe
Book page: 103-104 -- original C# listing
Converted from C# to Python.
aioodbc replaces DbConnection/DbTransaction async APIs; bare `raise` is C# `throw;`
and `raise ... from ex` is the inner-exception wrap; asyncio.shield keeps the
rollback running even if the caller is cancelled (CancellationToken.None).
"""
from __future__ import annotations
import asyncio
import os
import struct
from typing import Awaitable, Callable
import aioodbc
class TransactionRunner:
@staticmethod
async def run(
connection: aioodbc.Connection,
work: Callable[[aioodbc.Connection], Awaitable[None]],
) -> None:
# The connection is opened with autocommit=False, so work runs in a transaction.
try:
await work(connection)
await connection.commit()
except BaseException:
# Roll back even if the caller has cancelled.
await asyncio.shield(connection.rollback())
raise # same exception, original stack trace
class InvoiceExporter:
def export(self, invoice_id: int, folder: str) -> None:
path = os.path.join(folder, f"invoice-{invoice_id}.pdf")
try:
with open(path, "wb") as f:
f.write(self._render(invoice_id))
except OSError as ex:
# New exception adds context; the original is kept as __cause__.
raise RuntimeError(
f"Could not export invoice {invoice_id} to {path}.") from ex
@staticmethod
def _render(invoice_id: int) -> bytes:
return struct.pack("<i", invoice_id) # real rendering here
How it works
An exception's stack trace is captured when it is thrown. throw ex; is a new throw of the same
object, so the runtime resets the trace to the current method. throw; (only legal inside a
catch) rethrows the exception in flight and leaves the trace intact, so the log shows the
original failing line.
TransactionRunner uses a bare catch followed by throw;. That is one of the few places a
catch-everything block is correct: it doesn't handle the exception, it only guarantees cleanup.
Rolling back with CancellationToken.None makes sure a cancelled request still releases its
locks. If the work succeeded, the rollback never runs. If the commit itself fails, the rollback
runs and the commit's exception continues upward.
InvoiceExporter translates instead. The IOException alone says "the process cannot access the
file," which doesn't tell the reader which invoice or why it mattered. The new exception says
that, and InnerException keeps the full original, stack trace included. Logging frameworks print
the whole chain. That is what the ex parameter in LogError(ex, ...) is for.
Variations and pitfalls
throw ex;triggers analyzer warning CA2200. Make it an error in your.editorconfig:dotnet_diagnostic.CA2200.severity = error.- Wrapping without passing the inner exception (
throw new Exception("Save failed")) is worse thanthrow ex;. It loses both the stack and the original type and message. - Don't wrap at every layer. One translation at a meaningful boundary (repository to service, service to API) is enough. Five layers of "an error occurred" wrappers just make the log longer.
- Sometimes you need to rethrow later, outside the
catch, for example after trying a fallback.ExceptionDispatchInfo.Capture(ex)stores the exception, and.Throw()rethrows it later with the original stack trace preserved. - An exception filter (
catch (X ex) when (Log(ex))withLogreturningfalse) lets you log without catching at all, so the stack is never unwound. It's a neat trick, but use it sparingly; most readers don't expect it.