python - 如何在此程序中发现错误?
问题描述
我试图在以下代码中捕获错误:
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
请指出我的错误。
解决方案
您在 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")
推荐阅读
- python - 由另一列组织的一列元素的堆叠条形图
- python - 弃用警告:QDesktopWidget.availableGeometry(int screen) const 已弃用 centerPoint = QDesktopWidget().availableGeometry().center()
- ios - 在 iOS 中将 mach_absolute_time 转换为 (nano) 秒 (objective-C)
- angular - 如何注入服务一些数据?
- python - pandas 中是否有任何正则表达式,我们可以在其中定义第一个和最后一个字符,以及介于两者之间的任何内容
- symfony - 为什么 TinyMCE 会删除我的自定义 mpdf html 标签?
- ruby-on-rails - Rails Action Mailer Preview 不起作用,因为没有测试单元
- mongodb - 如果条件 MongoDB 聚合
- c++ - 如何将字节数组的一部分转换为 std::string 并避免在堆上分配 char 数组?
- xpath - XQuery - 我如何计算和保存地图中的信息