Python exception get stack trace

Python Program to Print Stack Trace

Python Certification Course: Master the essentials

A stack trace , also known as stack traceback , traceback, or backtrace, prints all the function calls that took place before an error occurred. Python Print Stack Trace assists users in figuring out the cause of an error and solving it.

What is Stack Trace in Python?

A stack trace is used to display all the function calls before an error occurs. The error is reported on the final line of the stack trace. The stack trace also shows information and function calls related to the thrown error to help users locate and solve it.

How to Print Stack Trace in Python?

Method 1: Using print_exc()

In the following code snippet, the value of the denominator is set to 0 to view how Python print stack trace works. The traceback.print_exc() method in the except block prints the program’s location, the line where the error was encountered, and the name and relevant information about the error. The last line confirms that the entire code executes without hindrance.

Method 2: Using print_exception()

In the following example, since the list arr has indices from 0-4 trying to address index 5 throws an error. The traceback.print_exception(*sys.exc_info()) method in the except block prints the details and cause of the error. The last line printed confirms that the entire code executes successfully.

Читайте также:  Php функция echo пример

More Examples for Understanding

Example 1

In the following erroneous code snippet, blood_group is written as bloodgroup to see how Python print stack trace works. The displayed stack trace contains information about the type of error — NameError, that occurred because the referenced variable bloodgroup is not defined. The exception tells us that the variable, function, or class does not exist due to incorrect reference.

Example 2

In the following code snippet, the value for children is set to 0 to view how Python print stack trace works. The displayed stack trace contains information about the type of error — ZeroDivisionError, that occurred because the denominator is 0 .

Example 3

In the following example, since the list arr has indices from 0-4 trying to address index 5 throws an error. The traceback.print_exception(*sys.exc_info()) method in the except block prints the details and cause of the error. This example is used to add more depth to the stack for easy visualization. Initially the function h() is called followed by g() and finally f() where trying to address index 5 throws an error.

FAQs

Q: Which module is required for Python print stack trace?

A: Importing the traceback module helps to extract, format and print stack traces.

Q: What does a stack trace show?

A: A stack trace displays the call stack (set of active method calls) and provides information about the methods called before an error occurs. It helps developers to figure out what went wrong in the code.

Q: What information does the stack trace contain? The stack trace contains :

  • Traceback for the most recent call.
  • Location of the program.
  • Erroneous Line.
  • Type of error and relevant information.

Q: What is the difference between print_exc and print_exception?

print_exc print_exception
traceback.print_exc(limit=None, file=None, chain=True) traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
It accepts 3 parameters limit , file , and chain . It accepts 6 parameters etype , value , tb , limit , file , chain

Conclusion

  • In Python print stack trace to see the function calls that took place before an error occurred.
  • The stack trace information helps to locate and fix the error easily.
  • The traceback module in Python provides functionalities to deal with the stack trace.
  • The methods used to print stack trace are print_exception() and print_exc() .

Источник

Python: Print StackTrace on Exception!

Embedded Inventor

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)
 File "/home/main.py", line 9, in 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!

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

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

Now that we have refreshed our memories on what exceptions are, 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.

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.

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.

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.

Instead of the usual Traceback:

Traceback (most recent call last): File "main.py", line 1, in 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 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.

 File "/home/ei/Desktop/to_delete.py", line 11, in 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!

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

Posted on Last updated: June 30, 2023

Источник

Оцените статью