[英]Exception decimal.ConversionSyntax not caught
This appears to be a simple Python question but it's got me scratching my head.这似乎是一个简单的 Python 问题,但它让我摸不着头脑。 I would expect the following code to print "Caught [<class 'decimal.ConversionSyntax'>]".我希望以下代码打印“Caught [<class 'decimal.ConversionSyntax'>]”。
Instead of the specific except decimal.ConversionSyntax
exception handler being called, it falls through to the generic except Exception as ex
and prints out "Exception [<class 'decimal.ConversionSyntax'>] not caught in previous except clause".而不是调用特定的except decimal.ConversionSyntax
异常处理程序,而是通过通用except Exception as ex
并打印出“Exception [<class 'decimal.ConversionSyntax'>] not catch in previous except 子句”。
Am I missing something obvious?我错过了一些明显的东西吗? Appreciate any insights -- thanks!感谢任何见解 - 谢谢!
import decimal
amount = 'this is not a valid decimal string'
try:
amount = decimal.Decimal(amount).quantize(decimal.Decimal('.01'))
except decimal.ConversionSyntax as cex:
print(f'Caught {cex}')
except Exception as ex:
print(f'Exception {ex} not caught in previous except clause')
Running the code:运行代码:
$ python3 /tmp/decimal-exception.py
Exception [<class 'decimal.ConversionSyntax'>] not caught in previous except clause
Some diagnostics:一些诊断:
>>> try:
... decimal.Decimal(amount)
... except Exception as e:
... f = e
...
>>> f
InvalidOperation([<class 'decimal.ConversionSyntax'>])
>>> f.__class__
<class 'decimal.InvalidOperation'>
decimal.InvalidOperation
is the class you should actually be looking for. decimal.InvalidOperation
是您实际上应该寻找的 class 。 Even though the string representation of the exception mentions decimal.ConversionSyntax
, and that is indeed a subclass of decimal.InvalidOperation
, the base class is raised.即使异常的字符串表示提到decimal.ConversionSyntax
,而且这确实是decimal.InvalidOperation
的子类,但基础 class 还是被提出了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.