Errors in Python

Errors in Python

Just like many other programming languages python has a system for handling errors, which are commonly referred to as exceptions however there is a distinction between the two terms. Having a good understanding of this system and its errors is very much crucial for writing code that is less prone to errors and more robust.

Error vs Exception

Error is a broad term for any problem or interruption in a software system. Errors do not necessarily need to disrupt parsing (when the interpreter checks your code for language specific structure before execution), or break the execution during runtime, you could simply experience what is called a ‘logical error’, which is when the software runs but does not work the way that the developer intended it to. Here is an example:

Developer Sam wants to normalize a data set and write the normalized data to a new file without modifying the original data. However, Sam realizes that while he does indeed generate a new file, the original non-normalized data is being modified as well. Sam will have to debug/refactor the code to fix this logical error. Note that Sam’s program runs without disruption

Types of errors in python.

  • Logical Error: As we discussed above, a logical error is when the software does not work as intended, but still runs without disruption.
  • Syntax Error: This error occurs before the program is executed and indicates that you did not adhere to pythons’ syntactical requirements. Before our code is executed the python interpreter, written in C and commonly referred to as CPython will parse the code to make sure it is adhering to the syntax requirements defined by PEP (python enhancement project) and pythons core developers. If there are errors found during parsing the code will never even execute, and you will encounter a syntax error. Let’s break down the common syntax errors:
    • Misuse or misspelling of python keywords like Class, for, while, etc
    • Forgetting or misplacing delimiters, like [], {}, “”, ‘’ (we use these to delimit a data type/object in python)
    • Misuse of or missing the colon “:” which serves as a separator
for="bill"
Syntax error: invalid syntax
  • Indentation Error: This is a subset of syntax error, simply created to clearly identify the misuse or misplacement of a tab. Tabs are an integral part of python, chose over curly brackets for increased readability.
    def error_finder():
IndentationError: unexpected indent
  • Runtime errors (exceptions): These are known as exceptions and occur at runtime; they can occur immediately upon execution or can be triggered during different processes of the program. These errors are an integral part of programming, and you can be sure that you will consistently and frequently encounter these. Python gives us tools to handle these errors that we need to be familiar with.
          • The famous ZeroDivisionError occurs when you try and divide by zero.
          • NameErrors will occur when you have an unresolved reference. This can happen when you are trying to use a variable that doesn’t exist, is in the wrong scope, or is used before it has even been defined. Typically, this will execute immediately, and you can use the exception trace to fix this.
          • TypeErrors occur when you try to apply functionality to an object of the wrong type, for example you may try to add an integer to a string (“5” + 5)
          • ValueErrors occur when you try to cast an object to an incompatible data type, for example trying to cast “bill” into an int. this can occur often when accepting user input, as all input is returned as a string. This can be prevented by checking the data before you attempt to cast it or by catching it (we will discuss this later).
        
        age = int(input("enter your age: "))
        ValueError: invalid literal for int() with base 10: 'ten'
        
      • KeyErrors occur when you attempt to use a dictionary key that doesn’t exist, for example you have a dictionary:
      cars = {"ford": "f150", "toyota": "camry"}
      
       ##Now you try to access a key in this dictionary that doesn’t exist
      
      cars["honda"]
      KeyError: 'honda'
      

      A good way to protect yourself is to use the dictionary “.get()” method, which  returns None instead of an error if the key is not found.

      cars.get("honda")
      • IndexErrors occur when you try to access an index that is out of range, this is similar to a KeyError, but occurs on lists and tuples.
      • AttributeErrors occur when you attempt to access an attribute/property or method that is not available to that object
cars = {"ford": "f150", "toyota": "camry"} 
cars.find() 
AtributeError: 'dict' object has no attribute 'find' 

As we can see a dictionary object does not posses an attribute or method named “find()”

      • FileNotFoundErrors are also very common and occur when python cannot find a file that you are attempting to open.

with open("collstuff.txt", "r") as f:
    print(f.read())
FileNotfoundError: [Error 2] No such file or dirctory: 'collstuff.txt'

Keep in mind that this error will occur when in “r” or read mode, and will create a non-existing file when in “w” or write mode.

Catching exceptions

One of the best tools at our disposal is try/except/finally which can only be used on runtime errors. The idea is to try or attempt to execute some code, and if an exception occurs than python will raise the exception at the except block. It’s always best to write your code in a way that reduces errors and the need for a try/except, but it’s impossible to prevent all exceptions all the time. Most developers will exclude finally, but it has potential use cases. Let’s explore an example.

def area_calculator(): 
      try:  # we know that a ValueError can occur here, so we are telling python to "try this code" 
          length = float(input("please enter the length of your object: ")) 
          width = float(input("please enter the width of your object: ")) 
          height = float(input("please enter the height of your object: ")) 
  
     area = length * width * height 
except ValueError as e:  # here we want to catch the specific error that can occur however you can use a broad exception like except Exception as e or even just use except both of which are frowned upon print(e) 

except IndexError as e:  # this error wont occur, but I’m highlight the ability to catch multiple exceptions with try/except (remember your try block may be vulnerable many different exceptions) print(e) 

finally:  # if code executes successfully with no error or if the block catches and error python will still execute code in this finally block print("this block runs regardless")

These are the basics of errors in python, and as large and vast as the python ecosystem is, it’s accurate to say there is still more information to be explored about them. For more documentation please visit pythons official documentation.
image

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for Practice
Register New Account
Shopping cart