Q:

Python program to raise an exception

belongs to collection: Python Exception Handling Programs

0

Python program to raise an exception

All Answers

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

To throw an exception on a particular condition – we use the "raise" keyword.

In the below examples, we have two files:

  • MyLib.py: This file contains two functions GetInt() and GetFloat() to input Integer and Float number with exception handling.
  • Main.py: This is the main file in which we are importing the "MyLib.py" file and performing the raise an expiation operation.
    In the program, we will read marks and check whether entered value is between 0 and 100 or not, if the value is other than the range, we are throwing an error using the "raise" keyword.

MyLib.py:

def GetInt(msg):
 while(True):
  try:
     k = int(input(msg))
     return k
  except ValueError as e:
    print("Input Integer Only...")

def GetFloat(msg):
 while(True):
  try:
     k = float(input(msg))
     return k
  except ValueError as e:
    print("Input Real Number Only...")

Main.py:

import MyLib

try:
    k=MyLib.GetInt("Enter Marks: ")
    if(not(k>=0 and k<=100)):
        raise (Exception('Invalid Marks: Must Be Between 0 and 100'))
    print("Marks: ",k)

except Exception as e:
    print(e)

finally:
    print("Bye Bye")

Output:

RUN 1:
Enter Marks: 67
Marks:  67
Bye Bye

RUN 2:
Enter Marks: 120
Invalid Marks: Must Be Between 0 and 100
Bye Bye

RUN 3:
Enter Marks: 123Hindi
Input Integer Only...
Enter Marks: 12
Marks:  12
Bye Bye

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

total answers (1)

Python Program for Raising User Generated Exceptio... >>
<< ValueError Exception in Python with Example...