Home »
Python »
Python Programs
Python exception handling program (Handling divide by zero exception)
Here, we will see a python program for exception handling. We will see how to handle divide by zero exception and throw exceptions if the wrong type of value is entered?
By Shivang Yadav Last updated : December 20, 2023
Program description
The program takes input from the user and checks if the user has entered valid data types and then at last checks for the divide by zero exception.
Python exception
An exception is a Python object that represents error that occurs during the execution of the program and this disturbs the flow of a program. The method of handling such exception is exception handling.
Steps to handle type exception in Python
The steps to handle type exception in Python are:
- Step 1: We will take inputs from the user, two numbers.
- Step 2: If the entered data is not integer, throw an exception.
- Step 3: If the remainder is 0, throw divide by zero exception.
- Step 4: If no exception is there, return the result.
Python program to illustrate the type exception
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
Output
Run 1:
Enter First Number: 432.12
Invalid Input Please Input Integer...
Run 2:
Enter First Number: 43
Enter Second Number: 0
division by zero
Run 3:
Enter First Number: 331 2
Enter Second Number: 4
83.0
In this example, we have used the following Python topics that you should learn:
Python exception handling programs »