Python: Print StackTrace on Exception!

In this article we’ll be looking at printing just the StackTrace from the error message of an exception.

We’ll see how to print it to the output screen and how to save it to a file. We will also see how to customize the message further for maximum efficiency.

Without further ado, let’s begin!

For those of you in a hurry, here is the short version of the answer.

Printing StackTrace: The Recipe

The StackTrace part of an error message refers to the part where it displays all the function calls leading upto an exception.

If you are looking to print just this part instead of the whole exception message here’s how you could that:

import traceback
import sys
def func_with_error():
    x = 1/0
def my_func():
    func_with_error()
    
try:
    my_func()
except ZeroDivisionError as e:
    stack_trace = traceback.format_tb(sys.exc_info()[2])
    for line in stack_trace:
        print(line)

Output:

  File "/home/main.py", line 9, in <module>
    my_func()

  File "/home/main.py", line 6, in my_func
    func_with_error()

  File "/home/main.py", line 4, in func_with_error
    x = 1/0

We can also print the same thing to a file, this is helpful in cases where you need to log the exceptions that occurred so that you could refer to it in the future!

import traceback
import sys
def func_with_error():
    x = 1/0
def my_func():
    func_with_error()
    
try:
    my_func()
except ZeroDivisionError as e:
    stack_trace = traceback.format_tb(sys.exc_info()[2])
    f = open("error_file.txt", "w")
    for line in stack_trace:
      f.write(line)
    f.close()

Now you will have a file named error_file.txt that contains the same StackTrace we printed earlier!

For visual learners out there we have also made an interesting video on this topic!

If the above explanation raises more questions than answers, then don’t worry as this recipe was meant as a quick refresher for those who are already familiar with the topic.

The rest of this article is written from a beginner’s perspective, so find a quiet place and focus for the next 10mins, I assure you that everything will make sense as you reach the end of the article!

Printing StackTrace, A Detailed Look!

One thing that you and I can agree on is that errors are annoying. They come out of nowhere, with some random info and ask you to rectify it.

But, we also can agree that errors are inevitable! No matter how experienced you are in programming, errors will pay you a visit now and then. If that’s the case why not understand what they are and learn how to deal with them properly!

The Fundamentals

Let’s start with a quick refresher and see what “Exceptions” really are using a simple analogy

Exceptions, What are they?

If you fill your car’s fuel tank with water instead of gas, the engine will have no idea what to do with it and the engine will simply refuse to run.

Similarly, when the “Python interpreter” (the engine) does not know what to do with the “data” (water) that we gave it, the program will get stuck. The Exception object is just an error report generated by the interpreter giving us clues on

  • what went wrong? and
  • where in the program the problem is?

Sure there is more to Exception than that, but their main aim is to give us clues. So the next time when you think about exceptions, think of them as clues to solve an issue!

If you feel that your basics could use some boosting, I suggest reading the following article

Exceptions in Python: Everything You Need To Know!

Also to get a quick primer on how to go about printing exceptions, I suggest watching the following video

Now that we have refreshed our memories on what exceptions are and how to print them, let us next look at what does the error message contain and how StackTrace fits into it.

What does an Error Message contain?

There are 3 main details contained in an exception.

  • Exception Message (which we are about to learn)
  • Exception Type and
  • Stack-trace

You can see those 3 parts in the picture below.

These 3 details are packed together into an object of type “Traceback“, which is aptly named as these 3 details can help us trace back to the point of the error.

We have written another article explaining each of these parts and what is each of their role in debugging the problem. You can find that article in the link below.

Python: Details contained in an Exception

This article is focussed on the code snippets that you can use to print the StackTrace. If you wish to print the other 2 parts of the error message you can refer to the articles below.

Print just the message of an exception

Python: Printing Exception Type

Let us get back to the topic and learn how to print just the StackTrace!

Printing just the StackTrace

Now that we have covered the fundamentals, let us see some examples of how to print the StackTrace of an exception.

Our goal here is

Instead of the usual Traceback:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print("qwerty" + 123456)
TypeError: can only concatenate str (not "int") to str

We should print only the StackTrace part:

File "main.py", line 1, in <module>
    print("qwerty" + 123456)

This is a short and concise way to relay the StackTrace information. Hence its usefulness!

We’ll also look into how to print it to a file. This is useful in situations where a developer might want to log all the occurred errors and keep a record of it.

And lastly, we’ll also look into how to customize the StackTrace text to make it more readable.

And ofcourse as usual, all the topics have examples to maximize learning! 

I don’t want to keep you waiting, so let’s begin right away!

Printing the StackTrace on the output screen

To print the StackTrace on the output screen, let’s first create a program that will raise an exception when called:

def func_with_error():
    x = 1/0

def my_func():
    func_with_error()

If its not obvious, the error we will run into here is ZeroDivisionError on line-2.

Now let’s import the sys module which contains the functionality that contains the information about the StackTrace and the traceback module which will help us format and print the StackTrace.

Lets also wrap it up neatly inside a try-except block as shown below.

import traceback
import sys

def func_with_error():
    x = 1/0

def my_func():
    func_with_error()
    
try:
    my_func()
except ZeroDivisionError as e:
    stack_trace = traceback.format_tb(sys.exc_info()[2])
    for line in stack_trace:
        print(line)

The main part of the code we are interested in here is lines 12 to 15. Here

  1. We have caught the exception
  2. Then we took out the StackTrace with the help of the exc_info() method of the sys module
  3. Then we printed out one line at a time using a for-loop.

The sys.exc_info() method returns a list and index-2 in that list contains the StackTrace. This is then formatted using the traceback.format_tb() method, which returns a list of strings containing the lines of the StackTrace. This list is then printed out using the for-loop.

On running the code above the following output will be printed onto our screens.

Output:

  File "/home/ei/Desktop/to_delete.py", line 11, in <module>
    my_func()

  File "/home/ei/Desktop/to_delete.py", line 8, in my_func
    func_with_error()

  File "/home/ei/Desktop/to_delete.py", line 5, in func_with_error
    x = 1/0

Printing StackTrace to a file

Sometimes you might need to keep a record of errors that were raised during the execution of your program, so that you can look it up later for debugging.

To do this we’ll simply create a new file and write whatever we want there.

import traceback
import sys

def func_with_error():
    x = 1/0

def my_func():
    func_with_error()
    
try:
    my_func()
except ZeroDivisionError as e:
    stack_trace = traceback.format_tb(sys.exc_info()[2])
    f = open("error_file.txt", "w")
    for line in stack_trace:
      f.write(line)
    f.close()

You might have noticed that the program is similar to before, the only difference being that we are printing to a file instead of to the output screen!

Note: We’re using the “w” mode here to write. The “w” overwrites anything that existed in the file earlier. If you want to preserve the contents so that you can add stuff to the same file for multiple runs of your code you should use the “a” mode instead as this mode appends whatever we write to the end of the file.  

And with that I will end this article.

Congratulations on making this far! Not many have the patience and perseverance that you have!

I hope you found this article useful and you got some value out of it!

Here are some more articles that might interest you!

Related articles

Python: Details contained in an Exception

Print just the message of an exception

Python: Print Exception Type

Exceptions in Python: Everything You Need To Know!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn