An exception can be raised forcefully by using the raise clause in Python. It is useful in that scenario where we need to raise an exception to stop the execution of the program.
It helps us to define user defined checks
The syntax to use the raise statement is given below.
try: age = int(input("Enter the age:")) if(age<18): raise ValueError else: print("the age is valid") except ValueError: print("The age is not valid")
Enter the age:15
The age is not valid
Enter the age:25
the age is valid
Example :Raise the exception with message
try: num = int(input("Enter a positive integer: ")) if(num <= 0): # we can pass the message in the raise statement raise ValueError("That is a negative number!") else: print("number is ",num) except ValueError as e: print(e)
Enter a positive integer: 25
number is 25
Enter a positive integer: -143
That is a negative number!
Write a python program to take input for 2 numbers calculate and print their sum.
conditions: number should be >=0
try: a=int(input("Enter 1st nos")) b=int(input("Enter 2nd nos")) if(a<0): raise ValueError("First value is invalid") if(b<0): raise ValueError("Second value is invalid") c=a+b print("Sum = ",c) except ValueError as e: print("Error :") print(e)
Enter 1st nos 10
Enter 2nd nos 20
Sum = 30
Enter 1st nos -25
Enter 2nd nos 63
First value is invalid
Enter 1st nos 24
Enter 2nd nos -12
Second value is invalid