Python - Errors and Exceptions - Exceptions

Featured image

This article is a part of the Python - 101 series, you can access the full version of the series here:

Welcome to the tenth article of the Python - Coding 101 series, which is about Exceptions. After reading this article, you’ll learn:

The outline of the article is as follow:

In the last article, we have learnt about 3 different types of errors. If you have already read that post, you would remember that we have already mentioned Exceptions. As a quick review, an exception is raised when something goes wrong during runtime. Or in other words, an exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s instructions.

There are built-in exceptions, as shown in the figure below, and also user-defined exceptions.

source: DataCamp

In this article, we will discuss the most common types of exceptions to make you comfort with the feels of encountering exceptions. You will be very likely to see them several times in your coding career, so having knowledge in advance would be beneficial. I will also introduce exceptions handling in the latter part of the post. Exceptions handling makes your code more robust and helps prevent potential failures that would cause your program to stop in an uncontrolled manner.

1. Common types of exceptions

1.1. NameError

You are trying to use a variable that doesn’t exist in the current environment. Check if the name is spelled right, or at least consistently. And remember that local variables are local; you cannot refer to them from outside the function where they are defined.

>>> print(ans)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
 in 
----> 1 print(ans)

NameError: name 'ans' is not defined

1.2. TypeError

There are several possible causes:

1.3. KeyError

You are trying to access an element of a dictionary using a key that the dictionary does not contain. If the keys are strings, remember that capitalization matters.

>>> dt = {'key1': 'value1', 'Key2': 'value2'}
>>> dt['key2']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 in 
      1 dt = {'key1': 'value1', 'Key2': 'value2'}
----> 2 dt['key2']

KeyError: 'key2'

1.4. IndexError

The index you are using to access a list, string, or tuple is greater than its length minus one.

>>> ls = [1,2,3,4,5,6,7]
>>> ls[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 in 
      1 ls = [1,2,3,4,5,6,7]
----> 2 ls[100]

IndexError: list index out of range

To debug this error, immediately before the site of the error, add a print statement to display the value of the index and the length of the array. Is the array the right size? Is the index the right value?

2. Exceptions Handling

As stated in the beginning of the article, exception handling makes your code more robust and helps prevent potential failures that would cause your program to stop in an uncontrolled manner.

Imagine if you have written a code which is deployed in production and still, it terminates due to an exception, your client would not appreciate that, so it’s better to handle the particular exception beforehand and avoid the chaos.

There are four main components of exception handling, as shown below:

source: DataCamp

As a quick note here, you can use as many except as you want, an in each except you can specify as many Exceptions as you want.

Example:

>>> try:
...     print (ans)
... except NameError:  
...     print ("NameError: name 'ans' is not defined")
... except (TypeError, IndexError):
...     print ("Other errors occurred)
... else:  
...     print ("Success, no error!")
NameError: name 'ans' is not defined

In Python programming, exceptions are raised when errors occur at runtime. We can also manually raise exceptions using the raise keyword. We can optionally pass values to the exception to clarify why that exception was raised.

The raise keyword if often used when you want to manage the input to the program.

>>> try:
...     a = -1
...     if a <= 0:
...         raise ValueError("That is not a positive number!")
... except ValueError as ve:
...     print(ve)
That is not a positive number!