还行吧:
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'!")
我的尝试:
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")
问题是,如果输入字符串s
同时包含k和l,则函数string_error_raiser
将仅引发ValueError(我正在捕获),使我无法重新引发KeyError。我不知道如何解决这个问题。问题设计不好,还是我在这里遗漏了什么?
最佳答案
您可以将函数分为两个函数。每个检查一个特定的条件:
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'!")
然后,将每个调用放在一个单独的try/catch
块中: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'")
我邀请您阅读this answer:Once you exit a try-block because of an exception, there is no way back in.
关于python - 重新引发Python中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747424/