Home > Net >  How to capture DivisionUndefined error in decimal
How to capture DivisionUndefined error in decimal

Time:06-22

I'm trying to capture the DivisionUndefined error. However I can only capture the parent error InvalidOperation.

from decimal import Decimal, DivisionUndefined

try:
    Decimal('0')/Decimal('0')
except DivisionUndefined:
    print('spam')

Expected output:

spam

Actual output:

Traceback (most recent call last):
  File "C:\test.py", line 4, in <module>
    Decimal('0')/Decimal('0')
decimal.InvalidOperation: [<class 'decimal.DivisionUndefined'>]

CodePudding user response:

As you can see from the stack trace, the exception raised is not DivisionUndefined but InvalidOperation. So, in order to suppress the exception, you should catch InvalidOperation:

from decimal import Decimal, InvalidOperation

try:
    Decimal('0')/Decimal('0')
except InvalidOperation:
    print('spam')

If you really want to handle only the DivisionUndefined case, I guess that you can do something like this:

from decimal import Decimal, DivisionUndefined, InvalidOperation

try:
    Decimal('0')/Decimal('0')
except InvalidOperation as err:
    if err.args[0][0] is DivisionUndefined:
        print('spam')
    else:
        raise err

But I would not recommend that as neither the structure of the err.args nor the DivisionUndefined itself is documented.

And BTW, if you only want to supress the exception, you might want this:

from decimal import Decimal, InvalidOperation, getcontext

c = getcontext()
c.traps[InvalidOperation] = False
Decimal('0')/Decimal('0')
  • Related