Error Handling

Written by: Ferhawn Shaheen (9/18/2020)

Introduction

This lesson covers an important aspect of programming that becomes essential when working with more complex code and programs. It makes one's code less susceptible to errors and breaking. This lesson will cover some basic methods and forms of error handling for a broad range of programs.

Using while loops

One of the most common ways to catch errors is by utilizing while loops. This is done by using a while loop to iterate a command over and over again if it detects an error. The error is usually specified in the condition of the loop. It is also worth noting that this method is common when working user input.

The following is an example of utilizing this form of error handling:

user_sum = int(input("Give a number between 1 to 10: "))

while user_sum not in range (1, 11):
    user_sum = int(input("That is not valid. Please try again: "))

In this example, the user input asks for a specific number between 1 to 10 (inclusive). Since the input function itself cannot prevent the user from entering a number outside of the given range, a while loop is specified. Notice the condition is the opposite of what we want (user_sum not in range (1,11)). This makes it so the while loop will only exit if the user entered a valid response (the condition will then be false).

Try Except Statements

Definition

In try-except, there are three primary components. These include the try block, except block, and the finally block.

The try block lets an individual test code for errors (you try something). The except block lets one handle the error itself. The finally block will run its code regardless of what occurs in the try and except blocks.

Format and Example

When one is using try-except, they would often write it in this way:

try:
  print(x)
except NameError:
  print("Variable x is not defined!")
except:
  print("Check your code for more errors!")

Notice how there as an error in the header of the except block. This is utilizing an exception in Python to specify the specific error message used. Let's take a closer look at exceptions.

Exceptions

In Python, there are specific error messages (exceptions) that are given when a specific error occurs. In the case of a NameError, the exception specifies that a name for a variable is not defined or given. There are many more built-in exceptions that Python has. It may be useful to use these exceptions to give specific error prompts. This is the case in the example above.

A broad list of exceptions can be found here: https://docs.python.org/3/library/exceptions.html

Examples with finally

The following is an example of utilizing the finally statement in try-except. It may seem trivial at first, but having something run regardless of the other blocks actually has some uses. One of the most important is the closing of a file, which is depicted here.

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()

It is essential that files are closed after opening any. Not doing so can lead to a host of errors in your ensuing code. finally ensures that regardless of what is prompted or tested, the file will always close. Closing a file should always happen at some point in your code.

raise

The raise keyword is also helpful when one seeks to raise specific exceptions or error messages. The following exemplifies this:

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")

In some cases, it can also be helpful to utilize a built-in exception. Here is an example of this:

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")

Conclusion

This lesson covered some ways of implementing error handling in Python. Various methods exist beyond these, but the most important methods are covered in this lesson. Error handling is an essential part of creating viable programs that others can use. This skill is carried over into other programming languages as well.

Last updated