【发布时间】:2019-10-07 17:55:01
【问题描述】:
在我的异常处理中,我试图捕捉 ZeroDivisionError,但由于某种原因,代码仍在执行除以 0 并且没有返回错误。我一定做错了什么,但我似乎无法放置它。
我试图将除法移动到函数中的其他位置,并同时移动除法错误捕获。
filename = "numbers.txt"
def main():
total = 0.0
number = 0.0
counter = 0
average = 0
#Open the numbers.txt file
try:
infile = open(filename, 'r')
#Read the values from the file
for line in infile:
counter = counter + 1
number = float(line)
total += number
average = total / counter
#Close the file
infile.close()
except IOError:
print('An error occurred trying to read the file', end=' ')
print(filename, '.', sep='')
except ValueError:
print('Non-numeric data found in the file', end=' ')
print(filename, '.', sep='')
except Exception as err:
print('A general exception occurred.')
print(err)
except ZeroDivisionError:
print('Cannot devide by zero.')
else:
print('Average:', average)
print('Processing Complete. No errors detected.')
# Call the main function.
main()
我希望结果除以零时返回错误消息,但它返回零作为答案。
【问题讨论】:
-
你能分享你得到的输出吗?实际上你做了
except Exception as err。这就是为什么 -
至少,
except ZeroDivisionError应该高于except Exception as err,因为ZeroDivisionError派生自Exception。换句话说,在其当前状态下,ZeroDivisionError块将永远不会被命中,因为除以零将在Exception块中处理。 -
@0x5453 我刚刚将 except ZeroDivisionError 切换到最后一个 except ,但仍然没有运气。
-
我刚刚输入了一系列用于测试异常错误的数字。我已经尝试了所有的零,几个零。每次它拉回 0.0 作为平均值而不是给我一个 ZeroDivisionError
-
我推荐阅读How to debug small programs。这应该很容易通过调试器或简单地通过添加一些
print语句来解决。
标签: python exception divide-by-zero