处理Python3中的异常



我正在尝试运行这个:

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.

我的问题是,有没有办法我看不到这句话,";在处理上述异常的过程中,发生了另一个异常:;以及以上的一切。

您要查找的是使用from None1禁用异常链接。

raise对账单更改为

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

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

最新更新