ADVERTISEMENT
ADVERTISEMENT

Python program to print inbuilt exception statement while type of exception is occurred

Here, we will see a program that will print the exception statement which is provided by the Python libraries when an exception occurs.
Submitted by IncludeHelp, on March 14, 2021

Exception Handling in Python is the method using which exceptions are handled in python. Exceptions are errors that change the normal flow of a program.

All exceptions in Python programming language have their own statement (errors/warnings) that are by default returned. We will see one such statement here which is thrown when a TypeError exception occurs.

TypeOf Exception occurs when we put strict constraints over the type of the variable taken in consideration i.e. when the program defines the exact type of data required and it is not entered in that variable. This throws a typeError exception.

Program:

# Python Program for exception handling 

# Starting try block  
try:
    # Taking input from the user ... 
    # The input strictly needs to be an integer value...
    num1 = int(input("Enter number 1 : "))
    num2 = int(input("Enter number 2 : "))
    
    # Adding the two numbers and printing their result.
    numSum = num1 + num2
    print("The sum of the two numbers is ",numSum)

# except block 
except Exception as ex:
    print(ex)

Output:

Run 1: when both numbers entered are integer (no exception occurred)
Enter number 1 : 3
Enter number 2 : 5
The sum of the two numbers is   8

Run 2: when one of the values entered is not an integer. 
Enter number 1 : 45 
Enter number 2 : 54.2
invalid literal for int() with base 10: '54.2'

Explanation:

In the above code, we have created two variables num1 and num2 and taken user input for their values. Both the values entered need to be integer values only. And then we have printed their sum. If the user enters any value other than integer, an exception occurs which is handled using an except block that prints an in-build exception statement.

Python exception handling programs »



ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.