A developer writes a function that attempts to access a dictionary key that may not exist: def get_value(data, key): try: return data[key] except KeyError: return None. They call it as get_value({'a': 1}, 'b'). What is the result and why?
When data[key] is evaluated and the key 'b' is not found, a KeyError is raised. The except KeyError block catches this specific exception and executes its body, which returns None. The function then exits normally. This demonstrates how exception handling can provide a fallback value instead of crashing. The caller receives None as the result.
Why this answer
The function uses a try-except block to handle a potential KeyError. When the key 'b' is not found, the exception is caught, and the except block returns None. This provides a safe way to access dictionary values without causing the program to crash.
The caller receives None as the result of the function call.
Exam trap
The trap here is forgetting that the except block handles the exception, so no error is raised to the caller.