0
  1. 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'!")
  1. 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?

mss
  • 195
  • 1
  • 8

2 Answers2

0

You could split your function into two functions. Each one checks a specific condition:

def string_error_raiser1(s):
    if 'k' in s:
        raise ValueError("The string contains the letter 'k'!")

def string_error_raiser2(s):
    if 'l' in s:
        raise KeyError("The string contains the letter 'l'!")

And then, put each call in a sperate try/catch block:

s = input("Please enter a string below:\n")

try:
    string_error_raiser1(s)
except ValueError:
    print("ValueError: the string contains the letter 'k'")

try:
    string_error_raiser2(s)
except KeyError:
    print("KeyError: the string contains the letter 'l'")

I invite you to read this answer:

Once you exit a try-block because of an exception, there is no way back in.

ThunderPhoenix
  • 1,649
  • 4
  • 20
  • 47
0

Maybe like this:

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'")
except KeyError:
    raise KeyError("I re-raised this error because you told me")

print("wheeeeeee")
Jonatan Öström
  • 2,428
  • 1
  • 16
  • 27