Exception Handling in Python

Python Exception Handling

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications etc.

Programs on Exception Handling in Python 

#Divide by Zero Error using Python
try:
a=int(input(“Enter num1:”))
b=int(input(“Enter num2:”))
c=a/b
print(c)
except Exception:
print(‘Divide by ZERO Error’)
else:
print(‘Done!’)
OUTPUT:
Enter num1:2
Enter num2:0
Divide by ZERO Error
#Array Index Error using Python
a=[1,2,3]
try:
print(a[3])
except IndexError:
print(‘Invalid index’)
OUTPUT:
Invalid index
# File not found error – python exception
try:
    file= open(“D:/Test.txt”,”r”)
except IOError:
    print(“File not found”)
else:
    print(“The file opened successfully”)
    file.close()
OUTPUT:
The file opened successfully
#Raise error using Python
try:
    age = int(input(“Enter your age:”))
    if age<18:
        raise ValueError;
    else:
        print(“Eligible for vote”)
except ValueError:
    print(“Not Eligible for vote”)
OUTPUT:
Enter your age:18
Eligible for vote
#Arithmetic Exception using Python
try:
    a = int(input(“Enter a:”))
    b = int(input(“Enter b:”))
    if b is 0:
        raise ArithmeticError;
    else:
        print(“a/b = “,a/b)
except ArithmeticError:
    print(“Second number should be non-zero”)
OUTPUT:
Enter a:2
Enter b:0
Second number should be non-zero
Share
Share
Scroll to Top