How to Use pdb.post_mortem in Python
Automatically enter the Python debugger at the exact point where an uncaught exception occurred, allowing interactive inspection of the crash site.
Python code
16 linesimport pdb
import sys
def divide(a, b):
return a / b
def main():
try:
result = divide(10, 0)
print(f"Result: {result}")
except Exception:
# Enter post-mortem debugging when an uncaught exception occurs
pdb.post_mortem(sys.exc_info()[2])
if __name__ == "__main__":
main()
Output
> /path/to/script.py(5)divide()
-> return a / b
(Pdb)
How it works
The try/except block catches the exception, and pdb.post_mortem(sys.exc_info()[2]) passes the traceback object to start debugging at the crash location. You can then inspect variables, evaluate expressions, and step through the code interactively. This technique is invaluable for diagnosing unexpected errors in complex applications without scattering print statements.
Common mistakes
- Calling pdb.pm() instead of pdb.post_mortem()—both work, but post_mortem is more explicit.
- Forgetting to pass sys.exc_info()[2]—the traceback object is required.
- Placing post_mortem outside the except block, causing a NameError.
- Confusing post_mortem with set_trace()—the latter stops execution at a specific line, not at an exception.
Variations
- Use `pdb.pm()` inside the except block for the same behaviour with less boilerplate.
- Set the environment variable `PYTHONBREAKPOINT=pdb.post_mortem` to automatically invoke it on any exception.
Real-world use cases
- Debugging a failed API request in production code to inspect the exact state when an unhandled exception occurs.
- Investigating a rare crash in a long-running batch job by capturing the post-mortem traceback.
- Diagnosing a mysterious exception in a data-processing script during development.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.