【发布时间】:2019-05-05 06:50:02
【问题描述】:
这是 Python 中一个简单的异常处理问题。我尝试使用 map() 获取输入 a 和 b,但我不明白为什么会出现以下错误。
我的解决方案:
for i in range(int(input())):
a, b = map(int, input().split())
try:
print(a//b)
except BaseException as e:
print("Error Code: ", e)
输入:
3
1 0
2 $
3 1
输出:
Traceback (most recent call last):
File "Solution.py", line 3, in <module>
a, b = map(int, input().split())
ValueError: invalid literal for int() with base 10: '$'
【问题讨论】:
-
不要捕获 BaseException。它不会做你认为它会做的事情。它的提供正是为了提供正常代码不应捕获的异常。改为陷阱
Exception。 -
是的。如果需要,我也可以使用特定的例外,对吧?
-
越具体越好。将
Exception视为最不具体的允许,除非您将Iterator子类化或同样深奥的东西。
标签: python