Home > Enterprise >  ZeroDivisionError: as 'integer division or modulo by zero' but get as 'division by ze
ZeroDivisionError: as 'integer division or modulo by zero' but get as 'division by ze

Time:10-13

I want to get the exception of ZeroDivisionError: as 'integer division or modulo by zero' but I get as 'division by zero'.How can I get that. can anyone explain?

a=int(input())
b=[]
for i in range(a):
    b.append(list(input().split()))
    try:
        print(int(int(b[i][0])/int(b[i][1])))
    except Exception as e:
        print( "Error Code:", e)

CodePudding user response:

The Python exception is ZeroDivisionError:

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

If you are trying to handle the exception, do an:

except ZeroDivisionError as e:

instead of trying to match the exception description.

If this answer doesn't cover you, please expand on what your needs are and why, so that we help you.

PS A naïve way to accomplish what you seem to ask:

>>> try: 1/0
... except ZeroDivisionError:
...  raise ZeroDivisionError('integer division or modulo by zero')
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ZeroDivisionError: integer division or modulo by zero

CodePudding user response:

I'm sure you have a reason for wanting the specific error message (maybe to understand float vs int division) so I'll address that.

Even though there is only one divide by zero exception (ZeroDivisionError) it's given with a different error message depending on the types used and the operation involved.

If you're trying to get the integer division exception message ("integer division or modulo by zero"), you need to perform integer division specifically using // instead of /. Converting numbers to integers with int() before or after dividing doesn't make / perform integer division.

As an example of how the error messages vary depending on the types involved:

>>> 5 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 5.0 / 0.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
>>> 5 // 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 5.0 // 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float divmod()

The above pertains to Python 3. / division in Python 2 of two int objects where the denominator is zero would result in the "integer division or modulo by zero" message.

  • Related