【问题标题】:Handling Exception in Python3 [duplicate]在 Python3 中处理异常 [重复]
【发布时间】:2021-04-13 11:29:17
【问题描述】:

我正在尝试运行这个:

try:
    number = int(number)
except ValueError:
    raise InvalidValueError("%s is not a valid base10 number." % number)

所以,当我设置number = '51651a' 我得到了这个:

Traceback (most recent call last):
  File "test.py", line 16, in decbin
    number = int(number)
ValueError: invalid literal for int() with base 10: '51651a'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 51, in <module>
    print(decbin('51651a', True))
  File "test.py", line 18, in decbin
    raise InvalidValueError("%s is not a valid base10 number." % number)
__main__.InvalidValueError: 51651a is not a valid base10 number.

我的问题是,有什么办法我看不到“在处理上述异常期间,发生了另一个异常:” 以及它上面的所有内容。

【问题讨论】:

    标签: python-3.x exception error-handling try-except


    【解决方案1】:

    您正在寻找的是使用 from None 1 禁用异常链接。

    将您的 raise 语句更改为

    raise InvalidValueError("%s is not a valid base10 number." % number) from None

    并且只会引发您的自定义异常,而不参考最初捕获的 ValueError 异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      相关资源
      最近更新 更多