- Write a function that takes in an arbitrary string and raises a ValueError if the string contains the letter 'k', and a KeyError if it contains the letter 'l'.
This is ok:
def string_error_raiser(s):
if 'k' in s:
raise ValueError("The string contains the letter 'k'!")
elif 'l' in s:
raise KeyError("The string contains the letter 'l'!")
- Write a try/except block that calls that function on arbitrary input. It should print out some explanation if there's a ValueError, and re-raise any KeyErrors. It shouldn't be able to handle any other error types. If no error occurs, print "Home safe", and no matter what happens, print "wheeeeeee".
My attempt:
s = input("Please enter a string below:\n")
try:
string_error_raiser(s)
print("Home safe")
except ValueError:
print("ValueError: the string contains the letter 'k'")
# how to re-raise any KeyError here?
finally:
print("wheeeeeee")
The problem is that if the input string s
contains both k and l, then the function string_error_raiser
will only raise a ValueError, which I am catching, leaving me unable to re-raise the KeyError. And I don't see how to get around this. Is the problem badly designed, or am I missing something here?