【问题标题】:Python try except error, program crashesPython尝试除错误,程序崩溃
【发布时间】:2023-03-28 09:45:01
【问题描述】:
def install_build(install_info,source_url=None):
    if source_url is None:
        try:
            version_no = install_info["version_number"]
            build_no = install_info["build_number"]
            if version_no is None or build_no is None:
                raise ValueError("Please specifiy the value(s) for either the source_url or version number and the build number")
        except KeyError:
            print("You are missing either or both of these keys: version number or build number")
        # If the necessary parameters are present, call the method to install the build
        install_build_on_server(version_no,build_no,source_url)

if __name__ == "__main__":
    install_build(    
        {   
            "product_type":"abc",
            "username":"def",
            "version_number":None,
            "build_number":"123",
            "password":"xyz"
        }   
        )

上述方法尝试从 [安装程序的] 源 URL 安装构建,或者通过集体获取构建和版本号并查询构建存储库,获取存储库并安装构建。因此,源 url 可以是 None 或者 version_number 和 build_number 可以是 None 不能两者兼而有之。我已经为此编写了错误处理。但是我的应用程序无法处理上述场景的错误。谁能告诉我我错过了什么?

这是程序的输出:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    "password":"xyz"
  File "test.py", line 7, in install_build
    raise ValueError("Please specifiy the value(s) for either the source_url or version number and the build number")
ValueError: Please specifiy the value(s) for either the source_url or version number and the build number

【问题讨论】:

    标签: python python-2.7 error-handling try-catch try-except


    【解决方案1】:
    if version_no is None or build_no is None:
    

    应该是

    if version_no is None and build_no is None:
    

    【讨论】:

    • 如果我使用 and 条件,而不是 or,它不会打印错误消息,我的意思是没有引发异常。
    • 我的情况是,两者都应该有字符串值。所以如果 version_no 是 None 并且 build_no 有值,“AND”条件失败
    【解决方案2】:

    同时检查 和 : 如果 version_no 是 None 并且 build_no 是 None:

    由于您传递的 version_no 是 None ,这会在 (OR) 部分引发值错误。要么更改条件,要么在 version_no 和 build_no 中都传递 None 以外的值。

    【讨论】:

    • 如果我使用 and 条件,而不是 or,它不会打印错误消息,我的意思是不会引发异常。我的情况是,两者都应该有字符串值。所以如果 version_no 是 None 并且 build_no 有值,“AND”条件失败
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多