Try Except in python for "FileNotFound" 报错后不停止执行

Try Except in python for "FileNotFound" doesn't stop the execution after the error

我是“Try & Except”的新手,如果我的问题很新手,我很抱歉。我试图搜索原因但没有找到任何原因。

我正在尝试一个非常简单的尝试除了 read_csv:

try:
  cntrl = pd.read_csv(my_directory + file, sep='|')
except FileNotFoundError:
  logger.critical("file not found")

logger.info(f"file imported. Number of records: {len(cntrl )}")

所以,当我没有文件时,try and except 只是打印错误并移至“logger.info”代码的下一行以提供以下错误。

UnboundLocalError: local variable 'cntrl' referenced before assignment

代码不是应该在发现错误的时候停止,不继续下一步吗?当我 运行 没有 try 和 except 的 read_csv 代码时,它停止并抛出错误 FileNotFound.

您可以添加一些应该 运行 的代码,仅当 try 语句中的内容不会引发 except 状态 else:

除此之外,如果您希望代码在出现错误时停止,请在 except 语句中使用 sys.exit()

然而,正如 Aryerez 所说,try-except 语句的目的通常是防止代码崩溃。如果你想让它在发生错误时停止 运行ning,你可以完全删除 try-catch 语句。