1 min read

ZeroDivisionError Exception in Python

Handling Zero Division exceptions in Python
ZeroDivisionError Exception in Python
Zero Division error in Python

A ZeroDivisionError is raised when you try to divide by 0. This is part of the ArithmeticError Exception class.

Example 1

Code/Output

# integers
1/0
>>> ZeroDivisionError: division by zero

# floats
5.3/0
>>> ZeroDivisionError: float division by zero

# complex numbers
(1+2j)/0
>>> ZeroDivisionError: complex division by zero

Example 2 - decimal library

If you are working with a decimal library and you perform the division operation with a 0, you get a DivisionByZero error.

The DivisionByZero eexception is decimal libraries own exception type that derives from the ZeroDivisionError exception.

Code

from decimal import Decimal

x = Decimal(1)
print(x/0)

Output

decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]

Handling ZeroDivisionError in Python

You can handle ZeroDivisionError errors by using the same exception class in your except block.

Code

# integers
try:
    1/0
except ZeroDivisionError as e:
    print(e)


# floats
try:
    5.3/0
except ZeroDivisionError as e:
    print(e)

# complex numbers
try:
    (1+2j)/0
except ZeroDivisionError as e:
    print(e)

Output

division by zero
float division by zero
complex division by zero

Hierarchy of ZeroDivisionError

The ZeroDivisionError inherits from the ArithmeticError class, which in turn inherits from the generic Exception class.

->Exception
-->ArithmeticError
--->ZeroDivisionError

So you can catch all ZeroDivisionError exceptions using the ArithmeticError exception class too.

Code

# integers
try:
    1/0
except ArithmeticError as e:
    print(e, e.__class__)


# floats
try:
    5.3/0
except ArithmeticError as e:
    print(e, e.__class__)

# complex numbers
try:
    (1+2j)/0
except ArithmeticError as e:
    print(e, e.__class__)

Output

division by zero <class 'ZeroDivisionError'>
float division by zero <class 'ZeroDivisionError'>
complex division by zero <class 'ZeroDivisionError'>

Check out other Python Built-in Exception classes in Python.