为何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
相关产品推荐
相关产品推荐

