How to handle KeyError Exception in Python

Python exception is simply a Python object that occurs when uncommon conditions in the program interrupt the flow of the program. Such conditions will interrupt the program flow and execution and you will not be able to execute the code ahead.

In this tutorial, you will learn about the KeyError Exception and how to handle KeyError Exceptions in Python.

The KeyError Exception in Python

The KeyError Exception is an exception that occurs when you try to access a dictionary key that doesn’t exist. It is one of the many built-in exceptions. You can face it while working with dictionaries or any other key-value pair involving objects.

dic= {1: 'A', 2: 'B'}
print(dic[1])
print(dic[3])
A
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-4-ecebb47f92d8> in <module>
      1 dic= {1: 'A', 2: 'B'}
      2 print(dic[1])
----> 3 print(dic[3])
KeyError: 3

When an exception is raised, you can observe its traceback. This traceback further gives you an idea about the exception, what caused it and where.

KeyError Exceptions-How to handle them?

The exceptions thrown, though annoying at first, can be easily resolved through exception handling mechanisms. You can handle the KeyError Exception in 2 ways:

  1. Preventing the exception from occurring
  2. Catching the exception and further working on it

Preventing KeyError Exception

Using the get() method:

You can use the get() method when you don’t want to add the missing key-value pair to the dictionary but also don’t want an exception to occur.
If the key is not found, this method returns the default value specified. If no default has been specified, then it will default to None.
A simple example to understand the same:

dic= {1: 'A', 2: 'B'}
x = dic.get(3, 'catwoman')
print(x)
catwoman

In the above example, key 3 doesn’t exist. But you prevent the program by using the get() and specifying the default value as ‘catwoman’. The dictionary dic has only 2 values and the default value is stored in variable x.

A more practical example:

prices = { 'Apple' : 100, 'Banana' : 50, 'Grapes' : 40}
item = input('Get cost of: ')
price = prices.get(item)
if price:
  print(f'The cost of {item} is {prices[item]}')
else:
  print(f'The cost of {item} is not known')
Get cost of: mango
The cost of mango is not known

Using the setdefault() method:

You can use the setdefault() method when you don’t want an exception to occur and want to add the missing key-value pair to the dictionary but also don’t want an exception to occur. It is very similar to the above method. However, this method adds value to the dictionary.

dic= {1: 'A', 2: 'B'}
c = dic.setdefault(3, 'catwoman')
print(c)
catwoman

Here, they 3 with value catwoman is added to the dictionary.

Catching the Exception

In some cases, you may not be able to catch the exception. In such a case, you can just log in the information about the exception and use it to resolve the same later on. You are aware now that whenever you encounter an exception, you can see all the information regarding the same in the traceback.
However, if the program crashes, you will lose this information. Hence, you can log this information by making use of the try and except clause.

import traceback
try:
  dic= {1: 'A', 2: 'B'}
  print(dic[3])
except KeyError as err:
  print("Key not known: ", err)
  traceback.print_exc()
Key not known:  3
Traceback (most recent call last):
  File "<ipython-input-17-29100e93c9b7>", line 4, in <module>
    print(dic[3])
KeyError: 3

Here, the code statements that can cause an error have been placed under try. If an Exception occurs, it is caught by the except clause and you can then assign the exception object to a variable(err). Later you can print the exception information using this variable. The traceback.print_exc() prints the stack trace and you can use this to check where the Exception object is.

An important read to understand better- Python Traceback.

Also read, Standard Exceptions In Python.

Leave a Reply

Your email address will not be published.