Exceptions
Exceptions
KeyError
If you try to read or pop or delete a key from a dictionary which does not exist, a KeyError
is raised. This is similar to the IndexError
you’ve seen in the cases of lists and tuples.
If you encounter a KeyError
it means the specified key does not exist in the dictionary.
>>> furniture = {'living room': ['armchair', 'sofa', 'table'],
... 'bedroom': ['bed', 'nightstand', 'dresser'],
... 'office': ['desk', 'chair', 'cabinet']}
>>> furniture['kitchen']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'kitchen'
If you try to remove an element from a set with .remove()
and the element does not exist within the set, you’ll get a KeyError
.
>>> silly_words = {'foo', 'bar', 'baz', 'quux'}
>>> silly_words.remove('garply')
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
silly_words.remove('garply')
~~~~~~~~~~~~~~~~~~^^^^^^^^^^
KeyError: 'garply'
If you want to remove an element from a set, and you aren’t sure it exists, and don’t want to use in
to check first or a try
/ except
, then you can use .discard()
.
>>> silly_words = {'foo', 'bar', 'baz', 'quux'}
>>> silly_words.remove('garply')
>>> silly_words
{'quux', 'foo', 'baz', 'bar'}
TypeError
If you try to add to a dictionary a key which is not hashable, Python will raise a TypeError
:
>>> d = {[1, 2, 3]: 'cheese'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
If you try to add an element to a set which is not hashable, Python will raise a TypeError
:
>>> s = set()
>>> s.add(["I", "am", "not", "hashable!"])
Traceback (most recent call last):
File "<python-input-7>", line 1, in <module>
s.add(["I", "am", "not", "hashable!"])
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'
If you try to create a named tuple, supplying the wrong number of arguments to the constructor, again, you’ll get a TypeError
.
>>> from collections import namedtuple
>>> Xyz = namedtuple('Xyz', ['x', 'y', 'z'])
>>> point = Xyz(5.2, 3.9)
Traceback (most recent call last):
File ".../interactiveshell.py", line 3553, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
...
TypeError: Xyz.__new__()
missing 1 required positional argument: 'z'
If you try to JSON encode a type which cannot be encoded, Python will raise a TypeError
:
>>> import json
>>> json.dumps(enumerate([1, 2, 3]))
Traceback (most recent call last):
File "<python-input-9>", line 1, in <module>
json.dumps(enumerate([1, 2, 3]))
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
...
TypeError: Object of type enumerate is not JSON serializable
AttributeError
Named tuples have fixed fields and field names. So if you try to access a field using a name that does not exist for the given type, you’ll get an AttributeError
.
>>> from collections import namedtuple
>>> Car = namedtuple('Car', ['make', 'model', 'year', 'color'])
>>> lesters_car = Car('Pontiac', 'Firebird', 1970, 'red')
>>> lesters_car.hp
Traceback (most recent call last):
File "<python-input-7>", line 1, in <module>
lesters_car.hp
AttributeError: 'Car' object has no attribute 'hp'
JSONDecodeError
A JSONDecodeError
occurs when we try to use json.loads()
or json.load()
to decode a string which is not a valid JSON-encoded string.
>>> import json
>>> json.loads("Dolittle: I do not understand the human race!")
Traceback (most recent call last):
File "<python-input-29>", line 1, in <module>
json.loads("Dolittle: I do not understand the human race!")
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
json.decoder.JSONDecodeError:
Expecting value: line 1 column 1 (char 0)
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.