I’m working on a Python script where I want to handle errors without crashing the entire application. I’ve wrapped some logic in a try/except block, which works fine, but I’m running into an issue when it comes to debugging.
Right now, I can catch the exception, but I only see the error message. What I really need is a way to python print stack trace information, the full traceback with file names and line numbers , just like Python shows when an exception isn’t caught, while still allowing the program to continue running.
try:
execute_task()
except Exception as exc:
print("An error occurred:", exc)
# I want to python print stack trace here
# without letting the exception terminate the program
What’s the correct or recommended approach to print or log the complete traceback from within the except block so I get full debugging details, but the script keeps running?
Thanks in advance for any guidance!
I usually go with Python’s built-in traceback module because it gives you full control over printing or logging the stack trace. You can do something like this:
import traceback
try:
execute_task()
except Exception as exc:
print("An error occurred:", exc)
traceback.print_exc() # This prints the full stack trace
This prints the same traceback you’d normally see if the exception wasn’t caught, and your program keeps running. Super handy for debugging loops or long-running scripts.
Sometimes I prefer capturing the stack trace as a string, especially if I want to log it or send it somewhere instead of printing to stdout. You can do this:
import traceback
try:
execute_task()
except Exception as exc:
error_details = traceback.format_exc()
print("Caught an error, full details:")
print(error_details)
This approach is nice if you’re integrating with a logging system or an error monitoring service. You can pass error_details directly to your logger without losing formatting.
If you want something more robust for real projects, I recommend using the logging module with exception info. This keeps your debugging info structured and configurable:
import logging
logging.basicConfig(level=logging.ERROR)
try:
execute_task()
except Exception as exc:
logging.error("Something went wrong!", exc_info=True)
Setting exc_info=True makes logging include the full traceback automatically. The program continues running, and you get neatly formatted logs instead of just a printout.
Personally, I start with traceback.print_exc() for quick debugging, and then move to logging.error(..., exc_info=True) when I want proper logs in production.
If you want, I can also show a one-liner approach that catches exceptions in loops and prints tracebacks inline, which is great for scripts processing multiple tasks.