By Lenin Mishra
This is the part of the 9th day in the Python 30 series. Check out the series here.
ZeroDivisionError is raised when you try to divide by 0. This is part of the ArithmeticError Exception class.
# 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 -
If you are working with a decimal library and you perform the division operation with a
0, you get a
DivisionByZero eexception is
decimal libraries own exception type that derives from the
from decimal import Decimal x = Decimal(1) print(x/0)
decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]
ZeroDivisionError in Python
You can handle
ZeroDivisionError errors by using the same exception class in your except block.
# 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)
division by zero float division by zero complex division by zero
Hierarchy of ZeroDivisionError
ZeroDivisionError inherits from the
ArithmeticError class, which in turn inherits from the generic
So you can catch all
ZeroDivisionError exceptions using the
ArithmeticError exception class.
# 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__)
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.
- Try, Except, Else and Finally in Python
- KeyError Exception in Python
- OverflowError Exception in Python
- ArithmeticError Exception in Python
- IndexError Exception in Python
- LookupError Exception in Python
- StopIteration Exception in Python
- TypeError Exception in Python
- NameError Exception in Python
- FileNotFoundError Exception in Python
- Catch Multiple Exceptions in Python