首页 > 解决方案 > 如何在此程序中发现错误?

问题描述

我试图在以下代码中捕获错误:

n=int(input("enter the first number: "))
m=int(input("enter the second number: "))
p=n/m
try :
    print( n/m)
except :
    print("dividing by zero may not be possible")
print(p)

这是输出

enter the first number: 5
enter the second number: 0
Traceback (most recent call last):
  File "py113.py", line 4, in <module>
    p=n/m
ZeroDivisionError: division by zero

请指出我的错误。

标签: pythonpython-3.x

解决方案


您在 try/except 块之外计算 p 。只需在 try 块中添加 p=n/m ,因此如果抛出异常,它将由 except 块处理。把 try 块想象成一个盒子,任何在盒子里面爆炸的东西都可以处理,如果在盒子外面爆炸就不能处理。

此外,建议您指定要尝试捕获的异常类型,因为可能会发生许多异常,例如“除以零”、“除以非数字”等……这似乎没有必要,但是当您有很多代码对调试很有帮助——否则你永远不会知道你的程序为什么会失败。

n = int(input("enter the first number: "))
m = int(input("enter the second number: "))

try:
    p = n/m
    print(p)    
except ZeroDivisionError:
    print("dividing by zero may not be possible")

推荐阅读