【发布时间】:2019-03-29 17:32:17
【问题描述】:
我正在尝试在 Python 2.7 中编写错误处理,以便在用户输入文件名后引发 IOError 异常。
我在互联网上尝试了几种解决方案,包括:
How to retry after exception? Get a Try statement to loop around until correct value obtained
这是我的原始代码:
while True:
try:
with open (userFile, 'r') as txtFile:
for curLine in txtFile:
curLine = curLine.rstrip("\n\r")
idList.append(curLine)
except IOError:
print("File does not exist")
每当引发 IOError 异常时,它都会进入一个无限循环,一遍又一遍地打印“文件不存在”。在我通过添加范围来限制尝试的情况下,它会通过该范围,一遍又一遍地打印,然后退出脚本。有谁知道为什么在引发异常时它会一直循环?
【问题讨论】: