8. 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”)
9. 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”)
13. 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”)
14. 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”)
20. Handling Exceptions in Invoked Functions
def fun(a,b):
try:
c=a/b
except ZeroDivisionError:
print(“You can not divide a no. by zero”)
a=int(input(“Enter the Number”))
b=int(input(“Enter the Number”))
fun(a,b)
21. def fun(a,b):
return a/b
a=int(input(“Enter the Number”))
b=int(input(“Enter the Number”))
try:
fun(a,b)
except ZeroDivisionError:
print(“You can not divide a no bye Zero”)
22. Programs
1. WAP that prompts the user to enter a number. If the
number is positive or zero, print it, otherwise raise an
exception ValueError with some message.
2. WAP which infinitely print natural numbers. Raise the
StopIteration exception after displaying first 20
numbers to exit from the program.
3. WAP that prompts the user to enter his name. The
program then greets the person with his name. But if
the person’s name is “Rahul”, an exception is thrown
explicitly and he is asked to quit the program.
23. Tricky Questions (Code 1)
1. What will be the output?
def fun():
try:
print("Hello")
return 1
finally:
print("DONE")
fun()
print("Hi")
24. 2. What will be the output?
def fun():
for i in range(5):
try:
if i==0:
print("Hello")
break
finally:
print("DONE")
fun()
print("Hi")
25. 3. What will be the output?
def fun():
for i in range(5):
try:
if i==0:
print("Hello")
continue
finally:
print("DONE")
fun()
print("Hi")