Python program to illustrate the import exception defined in another file and defining a new one

Here, we are going to learn how to define exceptions in one file and using it in another file in Python?
Submitted by Shivang Yadav, on February 14, 2021

An exception is a Python object that represents error that occurs during the execution of the program and this disturbs the flow of a program. The method of handling such exceptions is exception handling.

Here, we will define the method in one Python file and then import this exception in another file.

Step to create the exception file which will define type exception:

  • Step 1: Define the method for exception.
  • Step 2: Check for the input, if current input is of specific type no exception is there.
  • Step 3: Else, print exception.

Creating the main file

  • Step 1: Import the exception file.
  • Step 2: Call the method and check the exception and return the expectation based on the imported function.
  • Step 3: Here, we also need to check if enter marks are not in the range or not.
  • Step 4: Return the result as required.

Program:

ExceptionLib.py

def inputInt(msg):
    while(True):
        try:
            a = int(input(msg))
            return a
        except ValueError as e:
            print("Invalid Input..Please Input Integer Only..")

main.py

import ExceptionLib as E

while(True):
    try:
        h=E.inputInt("Enter Hindi Marks: ")
        if(not(h>=0 and h<=100)):
            raise(Exception("Invalid Marks (Marks can be between 0 to 100). You entered: "+str(h)) )
        else:
            break
    except Exception as e:
        print("Error: ",e)
    finally:
        print("Your marks is", h)

Output:

Run 1:
Enter Hindi Marks: 78
Your marks is 78

Run 2:
Enter Hindi Marks: 120
Error:  Invalid Marks (Marks can be between 0 to 100). You entered: 120
Your marks is 120
Enter Hindi Marks: 130
Error:  Invalid Marks (Marks can be between 0 to 100). You entered: 130
Your marks is 130
Enter Hindi Marks: 100
Your marks is 100

Run 3:
Enter Hindi Marks: 23.45
Invalid Input..Please Input Integer Only..
Enter Hindi Marks: 12
Your marks is 12

Run 4:
Enter Hindi Marks: Twenty Three
Invalid Input..Please Input Integer Only..
Enter Hindi Marks: 23
Your marks is 23

Python exception handling programs »





Comments and Discussions!

Load comments ↻





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