Register Login

Python KeyError Exceptions - How to Resolve it with Example

Updated Sep 26, 2019

Why KeyError is raised in Python?

In Python Language, KeyError raised when an invalid key is accessed from a dictionary. Either the key user tries to access does not exist or accessed an invalid key. Thus an error raised, this attempt of an invalid key is said to be KeyError.

Note: Dictionary is an unordered data structure where keys are map against the values.

Example

This Program may help you to understand this:

# We put three entries into dictionary.
values = {"a" : 1, "b" : 2, "c" : 3}
try:
 print(values["d"])
except KeyError:
 print("out of dictionary KeyError and there is no value of d")
print(values.get("d"))

Output 

$python main.py
out of dictionary KeyError  and there is no value of d

None

How to avoid KeyError Python to crash a program?

The keyError can be avoided with the help of Exception handling clause. When trying to access an undefined key-value form dictionary an exception is raised by python and program will crash, we can do it more gracefully be defining exceptions conditions in the exception block.

Try and except block will help you to avoid the keyError. The try and except is the keyword.

Try block statements will execute first then except. Everything executed well then except block will ignore.

Any error comes up the defined exception will be raised. Something which is not defined in the exception block raises some default exception.

Python KeyerrorMultiple exception clauses can be there with a Try statement block, to define and handle different exceptions errors and at least one either from an exception or else block exception must rise. It is as simple as that an exception is defined for every possible error.

import sys
try:
 op = open('file opening.txt')
 d = op.readline()
 a = int(d.strip())
except IOError as err:
 print("I/O error: {0}".format(err))
except ValueError:
 print("Data cannot to be change to integer .")
except:
 print("Unexpected error:", sys.exc_info()[0])
 raise

There can be optional else block too, it is used when an undefined exception is not raised.

Example:

import sys
try:
    op = open('file opening.txt')
    d = op.readline()
    a = int(d.strip())
except IOError as err:
    print("I/O error: {0}".format(err))
except ValueError:
    print("Data cannot to be change to integer .")
except:
    print("Unexpected error:", sys.exc_info()[0])
for arg in sys.argv[1:]:
    try:
        op = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        op.close()
    raise

As of now, we try to take care of program if any error like program crash by checking the data movement fetching /reading writing the data source and destination we wrote the exception according to, but any runtime error we still ignoring that in view of the program

Runtime error may arise in some certain situations. When a program tries to perform a read/write operation or some user input action, and some of the time value action performance like input required in numeric but user-inputted character value. The file is deleted /moved these type error /exception should be programmed prior assuming them.

In fact, the program is always understood a robust by user and programmer too handled such issues.


×