【问题标题】:ValueError Exception handling in PythonPython中的ValueError异常处理
【发布时间】:2020-03-20 18:37:53
【问题描述】:

我想在 Python 中处理 ValueError。但是每当我输入下面的代码时,我都会收到一个错误,我想要输出,因为我例外。

a, b = map(int, input().split())
try:
    print(a//b)
except ZeroDivisionError as e:
    print('Enter code: ', e)
except ValueError as e:
    print('Enter code: ', e)

如果我对 a 和 b 的输入是 '1' 和 '$' ValueError 的预期输出:'输入代码:int() 的无效文字,基数为 10:$

【问题讨论】:

标签: python python-3.x exception


【解决方案1】:

您的问题在您的try 之前,这里是a, b = map(int, input().split())

$ 被赋予int,这失败并引发invalid literal for int() with base 10: $,这是非常明确的

try:
    a, b = map(int, input().split())
    print(a//b)
except ZeroDivisionError as e:
    print('Enter code: ', e)
except ValueError as e:
    print('Enter code: ', e)

【讨论】:

  • 谢谢,对我很有帮助
  • @ShivManoharlalSharma 考虑阅读异常,它们很有帮助;)
  • @ShivManoharlalSharma 你现在可以考虑accepting the answer
猜你喜欢
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 1970-01-01
相关资源
最近更新 更多