How to catch and print full Python exception traceback without halting/exiting the program ?

To catch and print the full exception traceback in Python without halting the program, use the traceback module. Here’s how:

Method 1: Using traceback.format_exc()

import traceback

try:
    # Code that may raise an exception
    1 / 0
except Exception:
    # Print full traceback to stderr
    print(traceback.format_exc())

# Program continues execution
print("Program keeps running...")

Method 2: Using sys.exc_info()

import sys
import traceback

try:
    # Risky operation
    open("non_existent_file.txt")
except Exception:
    # Get exception details
    exc_type, exc_value, exc_traceback = sys.exc_info()
    # Format and print traceback
    traceback_details = traceback.format_exception(exc_type, exc_value, exc_traceback)
    print(''.join(traceback_details))

# Execution continues
print("Still running after error")

Key Features:

  • Full Traceback: Shows the complete error stack (file, line numbers, code context)
  • No Program Halt: Catches the exception but continues execution
  • Flexible Output: Can log to files instead of printing:
  with open("error.log", "a") as f:
      f.write(traceback.format_exc())

Example Output:

Traceback (most recent call last):
  File "demo.py", line 4, in <module>
    1 / 0
ZeroDivisionError: division by zero
Program keeps running...

Best Practices:

  1. Catch Specific Exceptions when possible:
   except ValueError as e:
       print(traceback.format_exc())
  1. Combine with Logging:
   import logging
   logging.basicConfig(filename='errors.log')

   try:
       risky_operation()
   except Exception:
       logging.error(traceback.format_exc())
  1. Preserve Original Error:
   except Exception as e:
       print(f"Error occurred: {str(e)}")
       print(traceback.format_exc())

This approach gives you detailed debugging information while maintaining program execution flow.

Leave a Reply

Your email address will not be published. Required fields are marked *