Updated April 11, 2023
Definition of Traceback in Python
Traceback in Python provides key to resolve unhandled exceptions that occur during the execution of the python program. This facility lists the nature of the exception, a clear explanation of the exception, and details of program segments in the reverse order of execution that has triggered the exception to occur.
File name, module name, line numbers, and the exact code displayed by the traceback module help developers to trace the causes of exceptions by linking back various program steps and zeroing in on the killer lines and correcting them for error-free execution. Traceback steps exactly match the action steps of the Python interpreter, and it improves the productivity of the developer in quickly resolving issues in the program.
Syntax:
Traceback details displayed by python contain several parts, and its syntax is:
Traceback (most recent call last)
Program segment (File name, Line no, module name, exact code) executed first
Program segment (File name, Line no, module name, exact code) executed second
….
Program segment (File name, Line no, module name, exact code) executed last
Exception name: Detailed exception message
A typical traceback looks like
Traceback (most recent call last): Traceback Header
First code that got executed
File “main.py,” line 23, in module1 File name main.py, line no 23, module-1.
Exact code-1 Code is displayed
Second in the execution list
File “main.py,” line 20, in module2 File name main.py, line no 23, module-2.
Exact code-2 Code is displayed
Last in the execution list
File “main.py,” line 17, in module3 File name main.py, line no 23, module-3.
Exact code-3 Code is displayed.
IndexError: list index out of range Exception name: Detail
How does Traceback work?
Python generates traceback when an exception occurs during the execution of the python program. There are two conditions the python program gets into problems while the program is executed.
One is a syntax error. If the program is not properly coded, the program gets into error at the time of compilation itself. The developer needs to write the correct code; then, only the program will progress to the next lines.
Two is the logical error called an Exception. This error happens only during the execution, and it surfaces only when an exceptional condition occurs within the program. The exceptional condition occurs due to the supply of wrong data, and the program is not designed to manage the extraneous condition.
There are several built-in exceptions available in python, and some of them are listed below:
1. ZeroDivisionError – This error occurs if some value is divided by zero. The denominator is zero in a division.
2. ImportError – Python throws this exception when a module called is not available in its repository, and the program cannot be executed.
3. IndentationError – Exception is thrown when the indentation is incorrect. Conditional statements like If, While, For need to follow certain indentation, and if it is not followed, this error will occur.
4. IndexError – When index referenced overflows the maximum limit defined in the program, this exception will be thrown.
5. KeyError – Python triggers this exception when the referenced key is not found in the mapped table or dictionary.
6. AssertionError – This exception is thrown when a condition is declared to be true by the using Assert statement before the execution, and slips into a false condition during the execution of the module. The program stops execution if this is found.
7. NameError – Python throws this error if an attempt is made to refer to a variable or a function that is not defined within the program. This error could occur if a local variable is referred out of its boundary condition.
8. AttributeError – This kind of error occurs if any assignment of value is attempted on a variable that contradicts its original attribute. A string value assignment on an integer variable or vice versa results in this error.
9. TypeError – Python throws this exception when a wrong operation is attempted on a variable. Arithmetic operation on a string variable or string operation on an integer variable results in this error.
10. MemoryError This error condition occurs when the program exceeds the memory allotted to it by creating too many memory spaces and not clearing them on time.
The developer will have to use the error details, trace the code steps that caused the error and understand the issues and correct the program accordingly.
Examples of Traceback in Python
Below are the different examples:
Example #1
In the example below, there is a provision to decode the month description for the first four months in the year Jan-Apr, and anything beyond this will result in index error.
# Program to decode month code of the first four months in the year
mthdesc = ["jan","feb","mar","apr"] # four month description is the table
def decodemth(mm): # Function decodemth to decode
print (mthdesc[mm]) # calls table, decodes, prints
def src(): # Working function src
monthcode =input ("Month code Please ") # Accepts month code
monthcode = int(monthcode) # Converts it into intger
monthcode = monthcode -1 # Adjust the offset
decodemth(monthcode) # Calls the decodemth function
src() # Calling working function
When the program is executed, it prompts month code. The screenshot under various inputs.
Month code = 02
Month code = 04
Month code = 08 (out of boundary condition)
The error thrown is index out of range. The first line to be executed is line 13, which calls the src() module. The second line is to be executed in line 11 in the src() module, which calls another module decodemth(monthcode). The third and last line to be executed in line 5, which decodes and prints and it is the place where the error is thrown.
Example #2
In this example, an arithmetic operation is attempted on a string, and it returns type error
# Program to decode month code of the first four months in the year
mthdesc = ["jan","feb","mar","apr"] # four month description is the table
def decodemth(mm): # Function decodemth to decode
print (mthdesc[mm]+1 ) # calls table, decodes, prints
def src(): # Working function src
monthcode =input ("Month code Please ") # Accepts month code
monthcode = int(monthcode) # Converts it into intger
monthcode = monthcode -1 # Adjust the offset
decodemth(monthcode) # Calls the decodemth function
src()
During execution with month code 01, it gives type error and traces lead to line 13
Example #3 – Indentation error
Under the function Division, the lines are not indented
def Division():
A = Num / Den
print ("Quotient ", A)
Num = int (input ("numerator "))
Den = int (input ("denominator "))
Division()
Example #4 – Division by zero error
def Division():
A = Num / Den
print ("Quotient ", A)
Num = int (input ("numerator "))
Den = int (input ("denominator "))
Division()
When the program is executed with 10 as the numerator and 5 as the denominator, it gives results correctly.
When the program is executed with 10 as the numerator and 0 as the denominator, it gives an error.
Conclusion
Traceback provides a lot of information, ways, and means to debug any error, locate the root cause and correct them for error-free execution of Python programs.
Recommended Articles
We hope that this EDUCBA information on “Traceback in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.