ReviseAlgo Logo

Debugging & Profiling

Traceback Analysis

Reading and understanding Python stack traces — traceback module, custom exception handling, and systematic error diagnosis.

Interview: Debugging fundamentals — reading tracebacks efficiently saves significant debugging time.

Last Updated: June 12, 2026 7 min read

A traceback (stack trace) shows the sequence of function calls that led to an exception. Reading tracebacks efficiently is a fundamental debugging skill — it tells you exactly where the error occurred and the call chain that caused it.

Reading a Traceback

  • Read from bottom to top — the last frame is where the error occurred
  • Bottom line: the exception type and message
  • Above that: the exact line of code that raised the exception
  • Higher frames: the chain of function calls that led there
  • Each frame shows: filename, line number, function name, code line

The traceback Module

  • traceback.print_exc() — print the current exception's traceback
  • traceback.format_exc() — return traceback as a string (for logging)
  • traceback.extract_tb(tb) — extract frame details programmatically
  • traceback.print_stack() — print the current call stack (no exception needed)
  • sys.exc_info() — get exception type, value, and traceback objects

Common Exception Patterns

  • AttributeError — accessing an attribute that doesn't exist (NoneType, wrong type)
  • KeyError — dictionary key not found (check if key exists or use .get())
  • IndexError — list/string index out of range (check length first)
  • TypeError — wrong argument type or number of arguments
  • ImportError — module not found or circular import
  • RecursionError — too many recursive calls (check base case)

Interview Insight

Read tracebacks from bottom to top — the error is at the bottom, the cause chain is above. Use traceback.format_exc() to capture tracebacks as strings for logging. In production, always log the full traceback with logger.exception() for post-mortem analysis.

Common Pitfall

Bare except: swallows all exceptions including KeyboardInterrupt and SystemExit. Always catch specific exceptions. Use except Exception: at minimum — it excludes system-level exceptions.

Use Cases

Production error logging — capturing full tracebacks for post-mortem analysis

Error reporting — sending tracebacks to monitoring services (Sentry, etc.)

Debugging — understanding the call chain that led to an error

Exception handling — catching specific exceptions with proper context

API error responses — converting tracebacks to user-friendly error messages

Common Mistakes

Bare except: — catches SystemExit, KeyboardInterrupt; use except Exception:

Swallowing exceptions — empty except blocks hide real errors

Not using raise from — loses the original exception chain and context

Reading traceback top-to-bottom — the error is at the bottom, read bottom-up

Not logging tracebacks in production — use logger.exception() to capture full context