Search code examples
pythonexceptiondivide-by-zero

ZeroDivisionError: as 'integer division or modulo by zero' but get as 'division by zero


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?

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)

Solution

  • 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