首页 > 解决方案 > 为什么代码到达异常块?

问题描述

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

标签: pythonexception

解决方案


您的错误是您忘记将答案转换为字符串,同时将其连接到您的打印语句,导致您的裸异常捕获了一个错误。关于裸异常的评论是完全正确的,所以我把它改成了 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!!!")

推荐阅读