What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Traceback: How to Read? & Error Types? (with Example)

  • Apr 12, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Python Traceback: How to Read? & Error Types? (with Example)

If the programmer is a beginner and comes across an exception in Python, the traceback output can be a bit overwhelming and a lack of understanding could easily disrupt lines of code. This is where Python Traceback comes into play. To become a good coder, one needs to comprehend what details a Python Traceback contains. 

What is Python Traceback?

Generally, in Python when an exception occurs a traceback will be printed frequently. Understanding what is a traceback and how is it caused can make the process of exception handling extremely simple. So, first, an individual needs to understand what it is, spot the problem in the line of code and correct it.

A Python traceback is used to handle an exception or trace an error that occurred in the line of code. When a Python program has a mistake, the interpreter can create a traceback that provides a series of function calls that went wrong and led to an error. The traceback contains every detail of the function calls like the stack's function name, line number, and file name.

Thus, this information is highly helpful in troubleshooting because it can detect the source of the error caused. It is a kind of report printed on the console useful for debugging.

Traceback Example

For instance, consider a Python program that throws exceptions every time a divisor is divided by zero and causes an error. Here, the traceback is created by the interpreter and displays all the function call details like the line number, file name, and series of function calls that resulted in the problem.

Using the tech information provided, an individual can easily locate the precise line of the code that produced the error as well as the functions which were called before that line of error, just by looking at the Python traceback.

python traceback example

 

Traceback (most recent call last):

File "example.py", line 10, in 

main()

File "example.py", line 6, in main

divide_by_zero()

File "example.py", line 2, in divide_by_zero

return 1 / 0

ZeroDivisionError: division by zero

 

Here, the divide by zero() code purposefully tries to divide 1 by 0, resulting in a ZeroDivisionError. Within a try block, the main() method performs divide by zero() and uses an except block to catch any exceptions that are thrown. And, the following Traceback will be seen after an individual runs the above code. 

Traceback (most recent call last):

File "example.py", line 10, in 

main()

File "example.py", line 6, in main

divide_by_zero()

File "example.py", line 2, in divide_by_zero

return 1 / 0

ZeroDivisionError: division by zero

 

To interpret the traceback in Python, first, we will check the top for the exception type and message. Then, we will look at the traceback entries after that. These are the active function calls with line number and filename. With this, you can guess where the error occurred. 

How to import traceback in Python?

The Python traceback module is an in-built module that offers capabilities and provides functionalities for using Tracebacks. Moreover, once an individual has imported the traceback module, it can be used to manipulate tracebacks, edit or print it too. The following syntax is used to import the traceback module: 

import traceback

Here is an illustration of how to print a traceback using the traceback module:

import traceback

def divide_by_zero():

return 1 / 0

def main():

try:

divide_by_zero()

except Exception as e:

traceback.print_exc()

if __name__ == '__main__':

main()

 

Common Traceback Errors

Concerning the specific program and circumstances, a traceback can be caused by any number of errors in Python. Below are a few typical traceback issues and the relevant pieces of the program, though:

  1. NameError: If a name is not present in the current scope, an error called a NameError will appear. For instance:
def main():

print(x)

if __name__ == '__main__':

main()

 

The traceback of the nameerror for the following program will be as follows:

Traceback (most recent call last):

File "example.py", line 4, in 

main()

File "example.py", line 2, in main

print(x)

NameError: name 'x' is not defined

 

  1. TypeError: Such type of errors occurs when the incorrect method or call is used on an object. For instance:
def main():

x = "3"

y = 4

print(x + y)

if __name__ == '__main__':

main()

 

The traceback of the typeerror for the following program will be as follows:

Traceback (most recent call last):

File "example.py", line 4, in 

main()

File "example.py", line 3, in main

print(x + y)

TypeError: can only concatenate str (not "int") to str

 

  1. ZeroDivisionError: Whenever a divisional operation is tried with a 0 as the denominator, the ZeroDivisionError takes place. For instance:
def main():

x = 5

y = 0

print(x / y)

if __name__ == '__main__':

main()

 

The traceback of the zerodivisionerror for the following program will be as follows:

Traceback (most recent call last):

File "example.py", line 4, in 

main()

File "example.py", line 3, in main

print(x / y)

ZeroDivisionError: division by zero

 

What is the use of the traceback module?

A Python traceback is a printed record of function calls that displays the call stack of the program whenever an exception occurs. The traceback module has several functions that let one modify and output Tracebacks in different ways, let’s look at some of them. 

  1. format_exc(): This function is mainly used to log a traceback or put it in a message if there is one. It returns a string that contains the whole Traceback. 
  2. print_exc(): This function outputs a file or the entire traceback to the console. It is mainly used in the except block of the try-except statement. 
  3. extract_stack(): This function is used to return a list of stack frames devoid of any formatting unique to Traceback.

Conclusion

One can figure out what is wrong with their Python code simply by using the useful information provided by traceback. This article covers everything about Python tracebacks for error handling. They can appear to be a little challenging, however, they may be really useful once individuals understand what they are trying to convey. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.