Q:

Python Program for Raising User Generated Exception

belongs to collection: Python Exception Handling Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to print inbuilt exception statemen... >>
<< Python program to raise an exception...