Friday, December 27, 2024
Google search engine
HomeLanguagesPython Traceback

Python Traceback

In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the code.The Python traceback contains great information that can help you find what is going wrong in the code. These tracebacks can look a little wearisome, but once you break it down to see what it’s trying to show you, they can be very helpful.

Consider following example…




# Python program to demonstrate
# traceback
  
  
mylist = [1, 2, 3]
print(mylist[10])


In this example, we are trying to access the 10th element of the list. With only 3 elements present in the list it will give Runtime error. When this program is executed you will get the following traceback.

Traceback (most recent call last):
  File "", line 2, in 
print(mylist[10])
IndexError: list index out of range

This traceback error has all the information about why this runtime error occurred. Last line of the traceback tells you about what type of error occurred along with relevant information. Previous lines of traceback points to the code in which error occurred. In the above example, the last line indicates the index occurred and the previous two lines show the exact location where the exception has occurred. let us now see, How to read traceback..

How to read traceback

Python traceback contains lots of helpful information about what exception is raised. Going through a few tracebacks line by line will give you a better understanding of the information they contain and help you get the most out of them, in this section we will see how to read a particular exception.

Python-traceback

In python it is best to read traceback from bottom to top.

  • GREEN BOX shows the what type of error occurred .
  • BLUE BOX shows the relevant information about error
  • ORANGE BOX shows traceback statement for recent calls, below The firstRuntime Error:
    Traceback (most recent call last):
    File “”, line 1, in
    ModuleNotFoundError: No module named ‘asdf’ line of each call contains information like the file name, line number, and module name
  • RED underlined part shows exact line where exception occurred.

Some of the common traceback errors are:

  • NameError
  • IndexError
  • KeyError
  • TypeError
  • valueError
  • ImportError /ModuleNotFound

Let’s go through each error one by one:

  1. NameError: NameError occurs when you try to reference some variable which hasn’t been defined in the code.

    Example:




    number = 1 
      
    # since no numb variable is
    # defined it will give NameError.
    print(numb)  

    
    

    Output:

    Traceback (most recent call last):
      File "gfg.py", line 5, in 
        print(numb)  
    NameError: name 'numb' is not defined
    
  2. IndexError: An IndexError is raised when a sequence is referenced which is out of range.

    Example:




    mylist = [1, 2, 3]
      
    # Accessing the index out
    # of range will raise IndexError
    print(mylist[10])

    
    

    Output:

    Traceback (most recent call last):
      File "gfg.py", line 5, in 
        print(mylist[10])
    IndexError: list index out of range
    
  3. KeyError: Similar to the IndexError, the KeyError is raised when you attempt to access a key that isn’t in the mapping, usually in the case of Python dict. Think of this as the IndexError but for dictionaries.

    Example:




    DICT ={ "a" :25, "b" :65 }
      
    # A is not mapped in dict
    # will raise KeyError
    print(DICT["A"])

    
    

    Output:

    Traceback (most recent call last):
      File "gfg.py", line 5, in 
        print(DICT["A"])
    KeyError: 'A'
    
  4. TypeError: TypeError is raised when an operation or function is applied to an object of inappropriate type. This exception returns a string giving details about the type mismatch.

    Example:




    c = 'b'+3
    print(c)

    
    

    Output:

    Traceback (most recent call last):
      File "gfg.py", line 1, in 
        c = 'b'+3
    TypeError: must be str, not int
    
  5. ValueError: A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.

    Example:




    print(int('xyz'))

    
    
    Traceback (most recent call last):
      File "gfg.py", line 1, in 
        print(int('xyz'))
    ValueError: invalid literal for int() with base 10: 'xyz'
    
  6. ImportError: The ImportError is raised when something goes wrong with an import statement. You’ll get this exception, or its subclass ModuleNotFoundError, if the module you are trying to import can’t be found or if you try to import something from a module that doesn’t exist in the module.

    Example:




    import module_does_not_exist
      

    
    
    Traceback (most recent call last):
      File "gfg.py", line 1, in 
        import module_does_not_exist
    ModuleNotFoundError: No module named 'module_does_not_exist'
    
RELATED ARTICLES

Most Popular

Recent Comments