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?
Submitted by Shivang Yadav, on February 13, 2021

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.

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:

  • 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.

Program to illustrate the type exception in python

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

Python exception handling programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.