Home »
Python »
Python programs
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 »