[英]try/except block catching multiple exceptions
我正在尝试创建一个尝试,但会捕获 3 个错误:
如果文件不是 txt 文件,我确实尝试执行第一个错误消息,但我也收到错误消息,说“str”object 没有属性“包含”
try:
file_name = input("Enter file name: ")
assert not file_name.contains(".txt")
except AssertionError:
("Error, must be a txt file")
file_fh = open(file_name)
counter = 0
avg = 0
for line in file_fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
avg += float(line[20:-1].strip())
counter = counter + 1
print("Average spam confidence:", round(avg / counter, 4))
如果您希望能够在大块代码中的任何地方捕获异常,则整个事情需要在同一个try
块中:
try:
file_name = input("Enter file name: ")
assert ".txt" in file_name, "Error, must be a txt file"
file_fh = open(file_name) # may raise FileNotFoundError
counter = 0
avg = 0
for line in file_fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
avg += float(line[20:-1].strip())
counter = counter + 1
assert counter, "File is empty!"
print("Average spam confidence:", round(avg / counter, 4))
except (AssertionError, FileNotFoundError) as e:
print(e)
在这个例子中,如果条件不满足, assert
语句显然会引发带有给定消息的AssertionError
。 如果文件丢失, open
调用将引发FileNotFoundError
,因此要处理这种情况,您需要做的就是确保您的except
块包含FileNotFoundError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.