简体   繁体   中英

Exception decimal.ConversionSyntax not caught

This appears to be a simple Python question but it's got me scratching my head. I would expect the following code to print "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".

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM