Home »
Python »
Python programs
Python Program for Raising User Generated Exception
Here, we are going to learn how to raising user generated exception with an example?
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.
Python programming language provides programmers a huge number of exception handler libraries that help them to handle different types of exceptions.
An exception is thrown when the code might go wrong and lead to an error. But when we explicitly want to raise an exception, we can do it by raising an exception with an explicit statement.
Program to illustrate raising user generated Exception in Python
# Python program to illustrate
# raising user generated Exception in python
# class to create user generated Exception...
class AgeError(Exception):
def __init__(self,message="Age must be greater than 0"):
self.__errormessage=message
def __str__(self):
return(self.__errormessage)
# Try block
try:
age = int(input("Enter Age : "))
if age<=0:
# raise AgeError()
raise AgeError("Age must be greater than zero")
else:
if age>=18:
print("You are eligible to Vote")
else:
print("You are not eligible to Vote")
# except Block
except AgeError as ex:
print(ex)
Output:
Run 1:
Enter Age : 43
You are eligible to Vote
Run 2:
Enter Age : 12
You are not eligible to Vote
Run 3:
Enter Age : -4
Age must be greater than zero
Explanation:
In the above code, we have created a class AgeError that inherits exceptions for creating and throwing user generated exceptions. The exception is thrown when a user enters a value 0 or less otherwise normal flow of code goes on. The code checks for eligibility of a person to vote.
Python exception handling programs »