python - 重新引发Python中的错误

标签 python error-handling try-catch

  • 编写一个函数,该函数接受任意字符串,如果字符串包含字母“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'!")
    
  • 编写一个try/except块,该块在任意输入上调用该函数。如果存在ValueError,它应该打印出一些解释,然后重新引发任何KeyError。它不应该能够处理任何其他错误类型。如果没有发生错误,请打印“家庭保险箱”,无论发生什么情况,请打印“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。我不知道如何解决这个问题。问题设计不好,还是我在这里遗漏了什么?

    最佳答案

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

    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/

    相关文章:

    python - django - 如何将表的记录与来自另一个表的计算计数值绑定(bind)

    python - 在 selenium 中抓取特定表

    php - error_handlers 页面在部署时不显示

    C fputc 错误处理?

    f# - 在 F# 中缩小 try-with block ?

    javascript - Node.js:为什么我的预期值没有在 'catch' 子句的 'try-catch' block 中返回?

    python - 单击按钮(python), Mechanize 和 Selenium 都有问题

    python - Pandas - 识别以列表中的值开头的数据框值

    c++ - std::chrono::steady_clock::now 如何报告错误?

    MS Access 数据库的 Java 登录表单问题