How to Debug Most Common Errors and Exceptions in Python (with Examples)

When getting started with Python, you will likely face exceptions. Exceptions in Python refers to the problems in your code.

When facing an exception in Python, something has gone wrong, which means you the programmer, have to debug what problem may exist in your code.

In this tutorial, we will learn to most common things that can go wrong with your code. We will also learn how to read and debug Python errors (traceback).

Join the Newsletter

    Reading the Python Error (Traceback)

    When you have an Exception in your Python code, you will get a traceback. A traceback is a message telling you what exception happened and where it happened.

    If you are interested to learn more, your can read my tutorial on the reading the Python traceback.

    Most Common Exceptions in Python

    • SyntaxError
    • IndentationError
    • ValueError

    SyntaxError

    A SyntaxError in Python is an exception that is raised when there is an error with the syntax of the programming language. Similar to how missing a dot at the end of a sentence would be an error in the English language, missing an colon could trigger a SyntaxError in Python.

    Here is are simple SyntaxError examples in Python:

    # Missing Colon
    if condition  # Missing colon
        # do something
    
    # Unclosed String
    my_string = "This is an unclosed string # Missing closing quote
    # SyntaxError: unterminated string literal (detected at line 1)
    

    For more information on how to fix SyntaxError in Python.

    IndentationError

    The IndentationError exception generally happens in Python when creating if…else blocks, defining a function, using loops or creating other blocks such as try… except statements. It most often occurs when there is no indentation, or when there is uneven indentation.

    # Not indented if block
    if True:
    print('not indented')
    # IndentationError: expected an indented block after 'if' statement
    
    # Uneven indentation
    def funct():
         print("Properly indented")
       print("Uneven indentation")
    # IndentationError: unindent does not match any outer indentation level
    

    For more information on how to fix IndentationError in Python.

    ValueError

    In Python, a ValueError most often occur when Python fails to make the conversion of one data type to the other.

    # Conversion Errors
    int("hello") # ValueError: invalid literal for int() with base 10: 'hello'
    float("3.14.159") # ValueError: could not convert string to float: '3.14.159'
    

    ModuleNotFoundError

    The ModuleNotFoundError exception happens when a library was imported but was not installed, or when the module was incorrectly cased or misspelled.

    # importing a package that was not installed
    import advertools
    
    # misspelling import
    import pandu
    
    # wrong casing
    import Pandas as pd
    

    IndexError

    my_list = [1, 2, 3]
    print(my_list[3])  # IndexError: list index out of range
    

    AttributeError

    my_list = [1, 2, 3]
    my_list.append(4)
    my_list.add(5)  # AttributeError: 'list' object has no attribute 'add'
    

    TypeError

    A `TypeError` occurs when an operation or function is applied to an object of inappropriate type.

    • Mismatched types in arithmetic operations
    • Function arguments of the wrong type
    • Indexing a non-indexable object
    • Calling a non-callable object
    • Using None in operations
    • Incompatible types in comparisons
    • Incorrect dictionary key type
    • Type mismatch in built-in functions
    # Mismatched types in arithmetic operations
    # Adding a string to an integer
    result = "Hello" + 5
    
    # Indexing a Non-Indexable Object
    # Indexing a data type that does not support it
    my_number = 123
    print(my_number[0]) 
    # TypeError: 'int' object is not subscriptable
    
    # Using None in Operations
    total = None
    total += 5
    
    # Incompatible Types in Comparisons
    result = "apple" < 5 
    
    # Type Mismatch in Built-in Functions
    int("3.14") 
    

    NameError

    IOError

    KeyError

    # import without alias
    import numpy
    numpy.ones(4)
    # array([1., 1., 1., 1.])
    
    # import without alias
    import numpy as np
    np.ones(4)
    # array([1., 1., 1., 1.])
    

    If a library is not installed, you will get the ModuleNotFoundError.

    Preventing RunTime Errors with Try… Except

    To prevent runtime errors in Python, you can use the try… except statements, which will work for exceptions that are not syntax related (SyntaxError, IndentationError).

    try:
        print(1 / 0)
    except Exception as e:
        print(e)
    
    Enjoyed This Post?