2

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'>]
aligen
  • 25
  • 4

1 Answers1

2

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')
radekholy24
  • 418
  • 2
  • 12
  • I ended up doing something like this: `except InvalidOperation as error: if 'DivisionUndefined' in str(error):` I'm not sure if this is better than your `if err.args[0][0] is DivisionUndefined` option, but thanks for the suggestion. – aligen Jun 21 '22 at 12:07