Exceptional Handling
Exceptional Handling
HANDLING
Vinay Agrawal
ASST. PROFESSOR
CEA DEPT.
GLA UNIVERSITY, MATHURA
Handling an Exception
Multiple except blocks
try:
statement(s)
except Exception1:
statement
except Exception2:
statement
except Exception3:
statement
Multiple Exceptions in a Single except
block
try:
n=int(input(‘Enter the number’))
print(n**2)
except (KeyboardInterrupt,
ValueError,TypeError):
print(“Please Check before you enter”)
print(“Bye”)
1. ZeroDivisionError
a=int(input(‘Enter the number’))
b=int(input(‘Enter the number’))
try:
c=a/b
print(c)
except ZeroDivisionError as e:
print(“Please Check Denominator ”,e)
print(“Bye”)
2. ValueError
try:
n=int(input(‘Enter the number’))
print(n**2)
except ValueError as e:
print(“Please Check before you enter ”,e)
print(“Bye”)
3.KeyboardInterrupt
try:
n=int(input(‘Enter the number’))
print(n**2)
except KeyboardInterrupt as e:
print(“Do not press ctrl+c ”,e)
print(“Bye”)
4. TypeError
(1) print(2+’Hello’)
(2) a=5
print(a())
(3) L=[1,2,3,4]
print(L[‘1’])
(4) a=45
for i in a:
print(i)
5. FileNotFoundError
fname=input(“Enter the filename”)
try:
fp=open(fname,’r’)
print(fp.read())
except FileNotFoundError as e:
print(“Please Check before you enter ”,e)
print(“Bye”)
6. PermissionError
fname=input(“Enter the filename”)
try:
fp=open(fname,’w’)
fp.write(‘Vinay’)
fp.close()
except PermissionError as e:
print(“Please Check the Permission of file
”,e)
print(“Bye”)
7. IndexError
L=[1,2,3,4]
try:
print(L[9])
except IndexError as e:
print(“Please Check the index ”,e)
print(“Bye”)
8.NameError
try:
print(a)
except NameError as e:
print(“Please Check the variable a ”,e)
print(“Bye”)
9. KeyError
D={1:1,2:8,3:27,4:64}
try:
print(D[5])
except KeyError as e:
print(“Please Check the key exists or not
”,e)
print(“Bye”)
Raising Exceptions
We can deliberately raise an exception using the
raise keyword
Syntax
raise [Exception [args]]
Example:
try:
n=10
print(n)
raise ValueError
except:
print(“Exception Occurred”)
Re-raise an Exception
try:
raise NameError
except:
print(“Re-raising the exception”)
raise
Handling Exceptions in Invoked Functions
def fun(a,b):
try:
c=a/b
except ZeroDivisionError:
print(“You can not divide a no. by
zero”)
fun()
print("Hi")