Reputation: 346
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
Upvotes: 0
Views: 1436
Reputation: 61519
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.
Upvotes: 1