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

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

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

问题

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

  1. def preprocess_corresponds_to_model(type_of_model: str) -> function:
  2. try:
  3. if type_of_model == "X":
  4. preprocessing_function = preprocess_location_df
  5. return preprocessing_function
  6. elif type_of_model == "Y":
  7. preprocessing_function = preprocess_event_df
  8. return preprocessing_function
  9. except FileNotFoundError as exception:
  10. raise Exception(
  11. f"The model {type_of_model} does not exist. "
  12. "The model should be either X or Y"
  13. ) 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.

  1. `def preprocess_corresponds_to_model(type_of_model: str) -> function:
  2. try:
  3. if type_of_model == "X":
  4. preprocessing_function = preprocess_location_df
  5. return preprocessing_function
  6. elif type_of_model == "Y":
  7. preprocessing_function = preprocess_event_df
  8. return preprocessing_function
  9. except FileNotFoundError as exception:
  10. raise Exception(
  11. f"The model {type_of_model} does not exist."
  12. "The model should be either X or Y"
  13. ) 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:

确定