PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How to capture DivisionUndefined error in decimal

 August 04, 2022     decimal, exception, python     No comments   

Issue

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'>]

Solution

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')


Answered By - radekholy24
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing