81.8k views
5 votes
1|>try:

2|>>some_function()
3|>except:
4|>>print("An error occurred!")
5|>[fill in this blank]
6|
Q: The code segment above attempts to call some_function, and catches any errors that result.
Imagine we wanted to modify this code so that we specifically catch KeyError and print "A KeyError occurred!". Which of the following code segments could we add to lines 5 and 6 to accomplish this?

User Andrfas
by
8.4k points

1 Answer

6 votes

Final answer:

To catch a KeyError and print a specific message, modify the code with 'except KeyError: print("A KeyError occurred!")'

Step-by-step explanation:

The code should be modified as follows:

except KeyError:

print("A KeyError occurred!")

The code 'except KeyError' will catch any KeyError that occurs and the message 'A KeyError occurred!' will be printed. This specific modification will ensure that only KeyError is caught and not any other type of error.

User Locksmith
by
9.1k points