[英]Python - Not recognizing Exception Handling
所以我在处理异常时遇到问题,我正在运行Python 3.6.3。 这是我的代码:
txt = ""
txtFile = input("gimme a file.")
f = open(txtFile, "r")
try:
for line in f:
cleanedLine = line.strip()
txt += cleanedLine
except FileNotFoundError:
print("!")
因此,如果我尝试输入错误而出错,而不是打印!
我仍然收到错误:
Traceback (most recent call last):
File "cleaner.py", line 11, in <module>
f = open(txtFile, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistentfile'
我尝试过在OSError
交换,我也尝试过except:
,这告诉我我做错了事(因为我一开始就不应该这样做),并且因为我明白, except:
应该捕获所有异常。
很简单,您要打开异常之外的东西。
txt = []
txtFile = input("gimme a file.")
try:
f = open(txtFile, "r")
for line in f.read().split('\n'):
cleanedLine = line.strip()
txt.append(cleanedLine)
except FileNotFoundError:
print("!")
您的尝试捕获是通过循环封装循环。
当您尝试在try块之外打开文件时发生错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.