异常 (try-except Exception) 为什么不起作用?

huangapple go评论52阅读模式
英文:

Why exception (try-except Exception) does not work?

问题

以下是您要翻译的代码部分:

def preprocess_corresponds_to_model(type_of_model: str) -> function:
    try:
        if type_of_model == "X":
            preprocessing_function = preprocess_location_df
            return preprocessing_function
        elif type_of_model == "Y":
            preprocessing_function = preprocess_event_df
            return preprocessing_function
    except FileNotFoundError as exception:
        raise Exception(
            f"The model {type_of_model} does not exist. "
            "The model should be either X or Y"
        ) from exception

希望这对您有所帮助。

英文:

Here is the code. For some reason, if I have type_of_model, neitehr X, nor Y exception does not work. The exception does not appear.

`def preprocess_corresponds_to_model(type_of_model: str) -> function:
    try:
        if type_of_model == "X":
            preprocessing_function = preprocess_location_df
            return preprocessing_function
        elif type_of_model == "Y":
            preprocessing_function = preprocess_event_df
            return preprocessing_function
    except FileNotFoundError as exception:
        raise Exception(
            f"The model {type_of_model} does not exist."
            "The model should be either X or Y"
        ) from exception`

I expect that when as an input parameter I have neither X, nor Y I will see an exception message and my python script will be interrupted. But nothing happens.

答案1

得分: 2

你在异常处理程序的范围内不打开任何文件。你返回一个在该范围之外调用的函数。因此,处理程序无效。

英文:

You do not open any files in the scope of the exception handler. You return a function which is called outside that scope. So the handler is ineffective.

huangapple
  • 本文由 发表于 2023年2月6日 21:18:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定