【发布时间】:2022-01-29 03:09:11
【问题描述】:
当我传递一个字符时,为什么except ValueError as ve 块没有被执行?
class Division :
def divide(numerator, denominator):
try:
print(f"Result : {(numerator/denominator)}")
except ValueError as ve:
print("Invalid input given",ve)
except Exception as e :
print(f"Exception caught : {e} ")
if __name__ == "__main__" :
a = int(input("Enter the numerator - "))
b = int(input("Enter the denominator - "))
divide(a,b)
O/P:
Enter the numerator - A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in Division
ValueError: invalid literal for int() with base 10: 'A'
相反,我希望看到print("Invalid input given",ve) 被执行。
【问题讨论】:
-
像这样使用
class完全没有意义。 -
在您调用
divide()之前,int(input(...))行上发生了错误。
标签: python valueerror except