【问题标题】:I have tried debugging this code but it doesn't seem to work我试过调试这段代码,但它似乎不起作用
【发布时间】: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


【解决方案1】:
>>> int('$')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '$'

a, b = map(int, input().split())

这里的这一行尝试将输入转换为 int,而您的第二行输入的 $ 不是有效整数。你应该尝试一下,除了:

for i in range(int(input())):
    try:
        a, b = map(int, input().split())
    except Exception as e:
        print("Error Code: ", e)
        continue
    try:
        print(a//b)
    except BaseException as e:
        print("Error Code: ", e)

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 2016-05-31
    • 2021-10-05
    • 1970-01-01
    • 2017-12-22
    • 2023-01-19
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多