C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Next: We trap the KeyError in a try-except construct. We print an error message in the except-block.
Finally: After handling exceptions, we access key "d" with the get() method. This is safe. No exception is raised.
ErrorPython program that handles KeyError
# Create dictionary with three entries.
values = {"a" : 1, "b" : 2, "c" : 3}
# Using the value directly can cause an error.
try:
print(values["d"])
except KeyError:
print("KeyError encountered")
# We use get to safely get a value.
print(values.get("d"))
Output
KeyError encountered
None
Also: If any direct accesses occur in your program, using a try-except block may be worthwhile if your code is new or untested.