【问题标题】:Re-raising errors in Python在 Python 中重新引发错误
【发布时间】:2020-10-26 01:37:50
【问题描述】:
  1. 编写一个函数,接收任意字符串,如果字符串包含字母“k”则引发 ValueError,如果包含字母“l”则引发 KeyError。

没关系:

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. 编写一个 try/except 块,在任意输入上调用该函数。如果有 ValueError,它应该打印出一些解释,并重新引发任何 KeyErrors。它不应该能够处理任何其他错误类型。如果没有发生错误,打印“Home safe”,不管发生什么,打印“wheeeeeee”。

我的尝试:

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。而且我不知道如何解决这个问题。问题是设计不当,还是我在这里遗漏了什么?

【问题讨论】:

  • 为什么要引发这两个异常?这是正常行为。程序在第一个引发的异常处停止。

标签: python error-handling try-catch


【解决方案1】:

您可以将函数拆分为两个函数。每个检查一个特定的条件:

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

一旦你因为异常退出了 try-block,就没有办法再进去了。

【讨论】:

    【解决方案2】:

    可能是这样的:

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2015-10-26
      • 2015-03-25
      相关资源
      最近更新 更多