Python program to illustrate importing exception from another file

Here, we will learn how to import exceptions to our python program from 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.

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.

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

Python exception handling programs »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.