Open In App

How to handle KeyError Exception in Python

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to handle KeyError exceptions in Python programming language.

What are Exceptions?

  • It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.
  • Exceptions are runtime errors because, they are not identified at compile time just like syntax errors which occur due to wrong indentation, missing parentheses, and misspellings. 
  • Examples of built-in exceptions in Python – KeyError exception, NameError, ImportError, ZeroDivisionError, FloatingPointError, etc.

What is KeyError Exception?

A KeyError Exception occurs when we try to access a key that is not present. For example, we have stored subjects taken by students in a dictionary with their names as a key and subjects as a value and if we want to get the value of a key that doesn’t exist then we get a KeyError exception. Let’s understand this by an example.

Example:

Python3




# Creating a Dictionary
subjects = {'Sree': 'Maths',
            'Ram': 'Biology',
            'Shyam': 'Science',
            'Abdul': 'Hindi'}
  
# Printing the subject of Fharan
print(subjects['Fharan'])


Explanation: In the above example we have created a dictionary and tried to print the subject of ‘Fharan’ but we got an error in the output as shown below because that key is not present in our dictionary which is called a Python KeyError exception.

Output:

Traceback (most recent call last):
  File "4119e772-3398-41b7-816b-6b20791538e9.py", line 7, in <module>
    print(subjects['Fharan'])
KeyError: 'Fharan'

Methods to handle KeyError exception

Method 1: Using Try, Except keywords

The code that can(may) cause an error can be put in the try block and the code that handles it is to be included in the except block so that abrupt termination of the program will not happen because the exception is being handled here by the code in the expected block. To know more about try, except refer to this article Python Try Except.

Example:

Python3




# Creating a Dictionary
subjects = {'Sree': 'Maths',
            'Ram': 'Biology',
            'Shyam': 'Science',
            'Abdul': 'Hindi'}
# try block
try:
    print('subject of Fharan is:',
          subjects['Fharan'])
# except Block
except KeyError:
    print("Fharan's records doesn't exist")


Explanation: In this example, subjects[‘Fharan’] raises an exception but doesn’t halt the program because the exception is caught by expect block where some action is being done (printing a message that “Fharan’s records doesn’t exist”)

Output:

Fharan's records doesn't exist

Method 2: Using get() method

The get() method will return the value specified by the given key, if a key is present in the dictionary, if not it will return a default value given by the programmer. If no default value is specified by the programmer, it returns “None” as output.

Example:

Python3




# Creating a Dictionary
subjects = {'Sree': 'Maths',
            'Ram': 'Biology',
            'Shyam': 'Science',
            'Abdul': 'Hindi'}
# Storing the subject of student
# that doesn't exist
sub = subjects.get('sreelekha')
# Printing the Subject
print(sub)


Output: In the above example, there is no key “sreeram” hence, it returns “None”.

None

If a default value is to be returned instead of “None”, we need to specify the default value in this way:  

sub = subjects.get(‘sreeram’, “Student doesn’t exist”)

Example :

Python3




subjects = {'sree': 'Maths', 'ram': 'Biology'}
sub = subjects.get('sreeram', "Student doesn't exist")
print(sub)


Output:

Student doesn't exist

To know more about exception handling in python please refer to this article Python Exception Handling.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads