Q:

Python program to illustrate importing exception from another file

belongs to collection: Python Exception Handling Programs

0

We will define an exception in a file which will check if the input is an integer or not. If yes, then do nothing otherwise throw an exception.

And then we will use this exception in our program.

All Answers

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

Program to illustrate importing of exception in python

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

num1=E.inputInt("Enter First Number: ");
num2=E.inputInt("Enter Second Number: ")

result=num1/num2

print(result)

Output:

Run 1:
Enter First Number: 100
Enter Second Number: 2
50.0

Run 2:
Enter First Number: 100
Enter Second Number: ok
Invalid Input..Please Input Integer Only..
Enter Second Number: Hello
Invalid Input..Please Input Integer Only..
Enter Second Number: -2
-50.0

Run 3:
Enter First Number: -100
Enter Second Number: 2.3
Invalid Input..Please Input Integer Only..
Enter Second Number: -3.4
Invalid Input..Please Input Integer Only..
Enter Second Number: 2
-50.0

Run 4:
Enter First Number: 100
Enter Second Number: 0
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    result=num1/num2
ZeroDivisionError: division by zero

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

total answers (1)

Python program to illustrate the import exception ... >>
<< Python exception handling program (Handling Type e...