我正在尝试编写一个简单的异常处理。但是,我似乎做错了。
def average():
TOTAL_VALUE = 0
FILE = open("Numbers.txt", 'r')
for line in FILE:
AMOUNT = float(line)
TOTAL_VALUE += AMOUNT
NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
print("the average of the numbers in 'Numbers.txt' is :",
format(NUMBERS_AVERAGE, '.2f'))
FILE.close()
except ValueError,IOError as err:
print(err)
average()
> line 14
> except ValueError as err:
> ^
> SyntaxError: invalid syntax
答案 0 :(得分:11)
这里有两件事不对。首先,您需要括号来包含错误:
except (ValueError,IOError) as err:
其次,您需要try
来使用except
行:
def average():
try:
TOTAL_VALUE = 0
FILE = open("Numbers.txt", 'r')
for line in FILE:
AMOUNT = float(line)
TOTAL_VALUE += AMOUNT
NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
print("the average of the numbers in 'Numbers.txt' is :",
format(NUMBERS_AVERAGE, '.2f'))
FILE.close()
except (ValueError,IOError) as err:
print(err)
如果没有except
,则无法使用 try
。