python - 捕捉 ZeroDivisionError
问题描述
在我的异常处理中,我试图捕捉 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()
我期望结果在除以零时返回错误消息,但它返回零作为答案。
解决方案
您需要更改捕获异常的顺序。由于 Python 中的所有异常都继承自 Exception 基类,因此您永远不会收到 ZeroDivision 异常,因为它是通过处理 Exception 捕获的。尝试这个:
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 ZeroDivisionError:
print('Cannot devide by zero.')
except Exception as err:
print('A general exception occurred.')
print(err)
else:
print('Average:', average)
print('Processing Complete. No errors detected.')
推荐阅读
- angular - 如何使用 [ngStyle] 将样式应用于 *ngFor 中的选定元素?
- javascript - 机车滚动:检测到元素但数据滚动速度不起作用
- reactjs - 根据条件调用组件
- user-interface - 有没有办法在不丢失本机 Windows 边框的情况下舍入 Delphi VCL 表单
- c++ - 我无法理解 if(std::cin>>) 循环
- javascript - 无法读取 null 的属性“cw”
- r - 并排的 Grobs 不适用于 Shiny
- python - 如何从 Python 中的列表定义图形连接(源、目标)?
- sql-server - T-SQL - 选择最新学年的结果
- powershell - 来自浏览器外部的 HTTP 请求被触发两次