Trace Exceptions to Their Failing Frames
Core idea
A traceback records the call path to an exception. Read the exception type and message, then identify the innermost relevant frame and the values that violated its contract. Outer frames explain how execution arrived there. A chained exception can preserve a separate original cause.
import tracebackdef parse(text): return int(text)def load(): return parse('bad')try: load()except ValueError as exc: frames = traceback.extract_tb(exc.__traceback__) print(frames[-2].name, frames[-1].name) print(type(exc).__name__)The last two frames locate the caller and failed conversion.
Expected output:
load parseValueErrorPreserve an original cause
def read_count(text): try: return int(text) except ValueError as exc: raise RuntimeError('invalid count') from exctry: read_count('x')except RuntimeError as exc: print(str(exc)) print(type(exc.__cause__).__name__)Explicit chaining adds domain context without losing the original error.
Expected output:
invalid countValueErrorCommon mistake
The final frame is not always the root defect: inspect callers and input assumptions. Avoid exposing raw tracebacks to users; messages and paths may contain private data.
Practice
Make load pass a valid number and then an empty string. Compare the failing frame and propose a validation boundary.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Traceback analysis
Check your understanding of traceback analysis.
What is printed?
try: int("x")except ValueError as e: print(type(e).__name__)What is printed?
try: try: int("x") except ValueError as e: raise RuntimeError("bad") from eexcept RuntimeError as e: print(type(e.__cause__).__name__)What should you inspect after the exception type?
Why use raise ... from exc?