Traceback most recent call last in python

Traceback is an error report occurring while executing Python code that throws an exception. It provides us traceback information about issues caused due to a certain piece of code.

Other programming languages such as java etc also throw such exceptions known as stack trace that we can diagnose by looking into error details with file name, line number, and executed code block (function, params, or another statement).

Traceback is very important for developers to know about problems containing information such as file name, function call, line number, and exception name. For beginners, traceback might be a little complicated to understand initially but it's a learning way to understand the problem with error reported and resolve it accordingly.

In python, it’s good to go through errors reported from bottom to top.

Let’s understand Traceback most recent call last in python with the following example:

def introduce():
	return "Hello, I'm Test python script"

print(introduces())
 

Result:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print(introduces())
NameError: name 'introduces' is not defined
        

Explanation: Here introduces() function is not defined in the program. This kind of error generally causes spelling/typing mistakes.

Now let’s understand the traceback error report in detail:

Line 1: Error message
Traceback (most recent call last):

Line 2: File "test.py", line 5, in
Exception caused at line number 5 of script test.py

Line 3: print(introduces())
Pointing code from where issue generated

Line 4: NameError: name 'introduces' is not defined
Contains traceback Exception name as “NameError”. With error message as “name 'introduces' is not defined” which is self-explanatory.

Note. NameError is reported if python tries to evaluate a variable, function, disc, etc which is not defined but used in the code block. Like in the above program it tries to evaluate introduces function but this function does not exist.

Traceback most recent call last in python

Let’s explore some common exceptions we met during program execution such as:

1. IndexError: list index out of range

Index out of range exception raised when we try to fetch items from the list by an index that does not exist.

Following code demonstrate list index out of range

employee = ["John", "Peter", "Alex", "Camren"]
print(employee[4])
    

Result:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print(employee[4])
IndexError: list index out of range

    

Explanation: Exception name as IndexError with error messages list index out of range. In the program, it tries to fetch values of the employee list that exist on index 4 but list employees have length 4 with index from 0 to 3. There is no item on index 4 therefore it complains once trying to run code employee[4].

Traceback (most recent call last): return error report containing line number and error name and relevant error message to identify the problem and apply fix accordingly.

Solution:

To avoid this index out-of-range issue we can check the condition before attempting index value

def getEmployee(index):
	employee = ["John", "Peter", "Alex", "Camren"]
	if(len(employee) <= index):
	 return "Index out of range"
	else:
	  return employee[index]

print(getEmployee(4))

    

Explanation:

Here we have a function getEmployee that receives index as argument and returns employee name based on a passing index. Condition len(employee) <= index check whether received index greater than or equal to the length of employee list. If the index is larger than the list length then it returns the message Index out of range else returns the employee name.

2. KeyError in the dictionary

KeyError is raised when we try to fetch an item usually from a dictionary that doesn’t exist.

Let’s understand with the following example code

def getEmployee(index):
	employee = {"J" : "John", "p" : "Peter", "A" : "Alex", "C" : "Camren"}
	return employee[index]

print(getEmployee("J"))

    

Result: John

Exaptation: All good. We have values associated with passing key J and return value as John.

What if we call the same function with another key that doesn’t exist. Evaluate for the key K as below

def getEmployee(index):
	employee = {"J" : "John", "p" : "Peter", "A" : "Alex", "C" : "Camren"}
	return employee[index]

print(getEmployee("K"))

    

Result:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print(getEmployee("K"))
  File "test.py", line 3, in getEmployee
    return employee[index]
KeyError: 'K'
    

Explanation: It raised Traceback (most recent call last): error report as KeyError and notifying us about key “K” with some details about function call and line number.

Solution: We can avoid KeyError issues by applying the required condition before fetching dictionary elements as below

def getEmployee(key):
	employee = {"J" : "John", "P" : "Peter", "A" : "Alex", "C" : "Camren"}
	if key not in an employee:
	  return "Key Doesn't exist!"
	else:
	  return employee[key]

print(getEmployee("K"))
    

Result: Key Doesn't exist!

Explanation: Condition key not in employee checks whether a received key exists in a dictionary or not.

If it exists, it returns relevant value to the calling function otherwise it returns a user-defined message Key Doesn't exist!

3. Modulenotfounderror (ImportError: No module named requests )

ImportError is raised while the python interpreter can’t find the imported package in the python script. There can be multiple reasons behind Modulenotfounderror such as

  • Spelling/Typing mistake in the imported module name
  • The included package is not installed
  • The interpreter can’t find the path of the included module.

The following example program demonstrates Modulenotfounderror

import requests
x = requests.get('https://www.quizcure.com')
print(x.status_code)
    

Result:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import requests
ImportError: No module named requests
    

Explanation:

Since requests are not installed on my server therefore while using the get function from requests package it complains and throws an exception as ImportError with the error message No module named requests.

Solution:

Install requests package.

pip install requests