Raising Exception Manually In Python

Raising Manual Exception In Python

  • raise is a keyword used to throw / return exception forcefully by a developer.
  • The benefit is to make stop abnormal termination of application and to provide a meaningful warning / message to user for better experience of the application

Syntax : 
                keyword raise Exception_name

Example : 



#program for raising manual exception

def check_age_for_DL_and_Validation(age):

if age >= 18 and age <= 50:
print("congrats, you are eligible for Driving Licence with 20 yrs of validity")

elif age < 18:
raise ValueError("Not eligible for Driving Licence right now, please apply later")

else:
raise ValueError("Eligible for Driving Licence with a validity of 5 years")

try :
age_1 =
int(input("age_1 :"))
check_age_for_DL_and_Validation(age_1)
age_2 =
int(input("\nage_2 :"))
check_age_for_DL_and_Validation(age_2)
age_3 =
int(input("\nage_3 :"))
check_age_for_DL_and_Validation(age_3)

except ValueError as VE:
print(VE)

 #Output with 1 st input a valid and 2nd input to raise a manual exception

age_1 :22
congrats, you are eligible for Driving Licence with 20 yrs of validity

age_2 :
55
Eligible for Driving Licence with a validity of 5 years

Process finished
with exit code 0


 #Output when all 3 entered ages are not throwing an exception

age_1 :22
congrats, you are eligible for Driving Licence with 20 yrs of validity

age_2 :
45
congrats, you are eligible for Driving Licence with 20 yrs of validity

age_3 :
34
congrats, you are eligible for Driving Licence with 20 yrs of validity

Process finished
with exit code 0


So the above 2 output scenarios conclude, the moment we raise an exception, try block will handover the exception to except block, and then application will not proceed inside try block from the instance of exception occurred.
If no exception raised, then all statements put under try will execute.

Suppose if the very first age is set to raise an exception


#Output when very first passed age throws an exception

age_1 :16
Not eligible for Driving Licence right now, please apply later

Process finished
with exit code 0






 

Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India