Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch KeyError Exception in Python?

When I run the following line of code, I get an error.

s = {'a':5, 'b':7}['c']

How do I catch this error and what type of error is it?


1 Answer
Manogna

A KeyError is raised when a value is not found as a key of a dictionary. The given code is rewritten as follows to catch the exception and find its type.

import sys
try:
s = {'a':5, 'b':7}['c']

except:
print (sys.exc_info())

OUTPUT

(<type 'exceptions.KeyError'>, KeyError('c',), <traceback object at
 0x0000000003203748>)
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.