DEV Community

Tommi k Vincent
Tommi k Vincent

Posted on

Getting the Traceback as a String in python

When Python encounters an error, it produces a treasure trove of error information called the traceback. The traceback includes the error message, the line number of the line that caused the error, and the sequence of the function calls that led to the error. This sequence of calls is called the call stack. Open a new file editor window in IDLE, enter the following program, and save it as error.py


def spam():
    bacon()
def  bacon():
    raise Exception('This is the  error message.')

spam()


Enter fullscreen mode Exit fullscreen mode

When you run error.py, the output will look like this

Traceback (most recent call last):
  File "/home/tommi087/Desktop/Development/code/phase-3/Automatingstuff/debugging/ErrorExample.py", line 6, in <module>
    spam()
  File "/home/tommi087/Desktop/Development/code/phase-3/Automatingstuff/debugging/ErrorExample.py", line 2, in spam
    bacon()
  File "/home/tommi087/Desktop/Development/code/phase-3/Automatingstuff/debugging/ErrorExample.py", line 4, in bacon
    raise Exception('This is the  error message.')
Exception: This is the error message.
Enter fullscreen mode Exit fullscreen mode

The traceback is displayed by Python whenever a raised exception goes unhandled. But you can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function. For example, instead of crashing your program right when an exception occurs, you can write the traceback information to a log file and keep your program running. You can look at the log file later when you’re ready to debug your program. Enter the following into a new file called errorExample.py:

import traceback

try:
    raise Exception('This is the error message.')
except:
    errorFile = open('errorInfo.txt', 'w')
    errorFile.write(traceback.format_exc())
    errorFile.close()
    print('The traceback info was  written to  errorInfo.txt.')
Enter fullscreen mode Exit fullscreen mode

This will be the output when the file is executed.

The traceback info was  written to  errorInfo.txt.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)