Python Practice › Exception Handling Programs › Program 3
Handle a missing dictionary key
Write a Python program that reads a key from a dictionary and handles a missing key.
Output
missing key: 'timeout' 30
Approach
- Catch
KeyError; compare withdict.get().
Solution
config = {"browser": "chromium"}try: print(config["timeout"])except KeyError as e: print("missing key:", e)print(config.get("timeout", 30))Output
missing key: 'timeout' 30
Line by line
Line 6
get with a default avoids the exception entirely when a default makes sense.
Learn the concept
New to this topic? Read the lesson, then come back.