You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何try-except Exception未生效?输入非X/Y时无异常触发

问题原因

你的代码里的try-except逻辑完全无效:

  • 当前try块里的if/elif判断根本不会触发FileNotFoundError,所以当传入的type_of_model既不是X也不是Y时,代码会直接跳过整个try-except结构,不会进入except分支抛异常。
  • 而且你捕获的FileNotFoundError和参数不匹配的场景完全不沾边,属于用错了异常类型。
修正后的代码

直接去掉多余的try-except,在参数不符合要求时主动抛出异常就行:

def preprocess_corresponds_to_model(type_of_model: str) -> function:
    if type_of_model == "X":
        return preprocess_location_df
    elif type_of_model == "Y":
        return preprocess_event_df
    else:
        raise ValueError(
            f"The model {type_of_model} does not exist. "
            "The model should be either X or Y"
        )

如果非要保留try-except结构(其实没必要,属于画蛇添足),可以改成这样:

def preprocess_corresponds_to_model(type_of_model: str) -> function:
    try:
        if type_of_model == "X":
            return preprocess_location_df
        elif type_of_model == "Y":
            return preprocess_event_df
        # 不符合条件时主动触发异常
        raise ValueError(f"Invalid model type: {type_of_model}")
    except ValueError as exception:
        raise Exception(
            f"The model {type_of_model} does not exist. "
            "The model should be either X or Y"
        ) from exception

内容的提问来源于stack exchange,提问作者Ololo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:45:26