使用Python 2,使用无效字符串创建Decimal会产生一个有用的错误消息:
>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 547, in __new__
"Invalid literal for Decimal: %r" % value)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/decimal.py", line 3872, in _raise_error
raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'spam'
虽然Python 3产生了一条不太有用的消息:
>>> import decimal
>>> decimal.Decimal('spam')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
有没有办法从Python 3中的异常中获取有用的信息,如“Decimal的无效文字:'垃圾邮件'”?
我在darwin上使用Python 2.7.15和Python 3.7.2。
附加物:
看起来Python 2曾经有一个非常有用的十进制消息.InvalidOperation:https://bugs.python.org/issue1770009
这种情况看起来很相似,但大多数情况都超出了我的想法:https://bugs.python.org/issue21227
你可以修补decimal
模块。
import decimal
def safe_decimal(something):
try:
funct_holder(something)
except Exception as e:
new_errror = Exception("Hey silly that's not a decimal, what should I do with this? {}".format(something))
raise new_errror from None
funct_holder = decimal.Decimal
decimal.Decimal = safe_decimal
然后你可以使用猴子修补版本
>>> decimal.Decimal('hello')
Traceback (most recent call last):
File "<input>", line 12, in <module>
File "<input>", line 6, in safe_decimal
Exception: Hey silly that's not a decimal, what should I do with this? hello