Catch and print full Python exception traceback without halting/exiting the program

2.0K    Asked by herath_7248 in Python , Asked on Nov 2, 2025

How can you catch and print the full Python exception traceback without stopping program execution?

What tools or modules allow you to log detailed error information while letting the script continue running?

Answered by Manish Nagar

In Python, you can catch exceptions and still keep the program running by using a try-except block. But to print the full traceback (not just the error message), you’ll want to use the built-in traceback module. This allows you to diagnose the issue without crashing the entire script.

 Basic Example Using traceback.print_exc()

import traceback
try:
    result = 10 / 0
except Exception:
    print("An error occurred, but continuing program...")
    traceback.print_exc()

  • Shows the full traceback, line numbers, and error type
  • Program continues running after printing the error

 Logging Instead of Printing (Recommended for real apps)

You can log the traceback to a file or console:

import logging, traceback
logging.basicConfig(filename="errors.log", level=logging.ERROR)
try:
    open("unknownfile.txt")
except Exception as e:
    logging.error("Exception occurred:
%s", traceback.format_exc())

 Why Use This Approach?

  • Debug errors without halting automation tasks
  • Useful in long-running scripts (web servers, schedulers, data pipelines)
  • Helps trace issues later through logs

 Alternative: Access the exception object

except Exception as e:
    print(e) # shorter but less detailed

By combining try-except with the traceback module, you maintain full visibility into errors while keeping your program alive — a powerful technique for building resilient Python applications.



Your Answer

Interviews

Parent Categories