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:2Enter num2:0Divide 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:18Eligible 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:2Enter b:0Second number should be non-zero