python - 为什么代码到达异常块?
问题描述
x=int(input("Enter the Dividend:"))
y=int(input("Enter the Divisor:"))
try:
ans=x/y
print('Answer:'+ans)
except:
print("Cannot divide it by zero!!!")
Enter the Dividend:12
Enter the Divisor:3
Cannot divide it by zero
解决方案
您的错误是您忘记将答案转换为字符串,同时将其连接到您的打印语句,导致您的裸异常捕获了一个错误。关于裸异常的评论是完全正确的,所以我把它改成了 ZeroDivisionError
x=int(input("Enter the Dividend:"))
y=int(input("Enter the Divisor:"))
print(x)
print(y)
try:
ans = x/y
print('Answer:'+str(ans))
except ZeroDivisionError:
print("Cannot divide it by zero!!!")
推荐阅读
- javascript - 如何重新启动已设置间隔的倒数计时器?Javascript
- azure - 如何将 Ubuntu VM 从 Digital Ocean 迁移到 Azure
- reactjs - 材质 UI 工具提示未在嵌套组件上呈现
- asciidoc - asciidoc:源块对齐到嵌套列表项
- python - sns pairplot 变量“GrLivArea”输出为空白
- c# - 将计算传递给字符串插值
- c# - c# JSON REST 响应通过 3 种不同的方法(WebRequest、RESTSharp、HttpClient)是空的,但 Postman 和浏览器可以工作
- c# - 删除 Swagger UI 上的架构 - 续
- cron - 每个月底运行工作的表达式:骆驼,石英
- stm32 - STM32 UART DMA可以第一次正确接收然后什么也没收到