In Mathematics, dividing any number by zero yields undefined result, because it is impossible to divide any number into zero parts. Python raises the ZeroDivisionError
exception when we attempt to divide a number by zero.
The ZeroDivisionError
is a subclass of the built-in ArithmeticError
exception. This set of exceptions are generally raised when an illegal mathematical operation is performed.
Handling the ZeroDivisionError Exception
When a ZeroDivisionError
occurs, it is usually accompanied by an error message indicating what operation was attempted. So you will easily tell that a division by zero was attempted and fix it.
It is also generally best practice to use a try...except statement to catch the error and handle it appropriately in cases where you expect the error to be raised. This allows the program to continue executing normally rather than crashing.
In the above example we get two input numbers from the user. If the second number is zero, we catch the ZeroDivisionError
exception that is raised and instead show the user a friendly error message.