Python program to raise an exception

Here, we are going to learn how to throw an exception using raise keyword in Python?
Submitted by IncludeHelp, on February 18, 2021

Problem Description: Write a Python program to demonstrate the raise keyword, how to raise an exception in Python?

Problem Solution:

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

Python exception handling programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.