# Handle Zero Division Error In Python

Last updated June 21, 2023 by Jarvis Silva

In this tutorial I will show you how to handle zero division error in python programming, zero division error is thrown when you try to divide a number by 0, as we learned in maths that we cannot divide a number by 0.

So in programming when a user try to divide a number by zero we have to handle it. So let’s see how to handle it in python.

## Python Code To Handle Divide By Zero Exception

``````
try:
numerator = float(input("Enter a numerator: "))
denominator = float(input("Enter a denominator: "))
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Cannot divide by zero.")
```
```

Above is code for zero division error handling, you can test this program by running it on your computer or using this online python compiler.

As you can see in the program I have used try and except statements. In the try block it will try to execute the code if any error it will be caught in the except block.

We are particularly catching the ZeroDivisionError by specifying it in the except. If anyone tried to divide by 0 it will print cannot divide by zero below is an example output.

``````
# If divide by number other then 0
Enter a numerator: 12
Enter a denominator: 6
2.0

#If divide by zero
Enter a numerator: 12
Enter a denominator: 0
Cannot divide by zero.
```
```

As you can see succesfully caught the error and the program is still running without exiting when the error occurs.

Here are some more python tutorials for you:

I hope you found this tutorial helpful and useful. Do share it with someone who needs it and if you want updates of our tutorials join our telegram channel.

Thanks for reading, Have a nice day 🙂