Python exception handling program (Handling Type exception)

Here, we see a program in Python to see the working of type exceptions in Python.
Submitted by Shivang Yadav, on February 13, 2021

Program description: The program takes input from the user and checks if whether the input value is an integer or not, if the input value is not an integer then the program will through a Type 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: Take input from the user.
  • Step 2: If the entered number is not an integer, throw an exception.
  • Step 3: If the entered number is an integer, print the integer.

Program to illustrate handling of type exception in Python

while True:
    try:
        num = int(input("Enter First Number: "))
        print(num)
        break
    except ValueError as e:
        print("Invalid Input..Please Input Integer Only..")

Output:

Run 1: 
Enter First Number: 43
43

Run 2:
Enter First Number: 123.1
Invalid Input..Please Input Integer Only..
Enter First Number: 43
43

Python exception handling programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.