Exception Handing
Exception Handing
(II) If exception handling is not done in a code, the program may abnormally close leaving
the user in a confusion.
Que 3. (A) (i) Differentiate else and except blocks in exception handling
(ii) Write a code to open a file readme.txt and print all its contents. Report an error if the
file doesn't exist.
Or
(B) (i) When is a ValueError exception raised in Python.
(ii) Is it compulsory to write the finally block in exception handling.
Ans. 3. (A) (i) except Carries code to handle / respond against the exception.
else Carries code that executes if no exception occurs.
(ii) try:
f1= open ("readme.txt")
str fl.read()
print (str)
fl.close()
except 10Error:
print ("File doesn't Exist")
Or
(B) (i) Raised when a function gets argument of correct type but improper value.
(ii) No, the finally block is optional and carries code that will execute, irrespective of
whether exception occurs or not.
Ques-3. (A) (i) When is the ImportError exception raised?
(ii) Which error is raised by the following code?
import pickle as p
try:
f=open("myfile.dat". "w")
p.dump(["1. "Sachin", "Accts"],"a")
f.close()
except:
print("Module not found")
Or (B) (i) When is ZeroDivisionError exception raised?
(ii) When is the code in else block executed?
Ans:- (A) (i) Import error is raised if the module being imported is not found.
(ii) ImportError
Or
(B) (i) ZeroDivisionError is Raised the code divides a number by a zero denominator.
(ii) No, the finally block is optional and carries code that will execute, irrespective of
whether exception occurs or not.
Ques-4.(A) (i) What is the use of except clause in exception handling?
(ii) Which error is raised by the following code:
import pickle as p
a=20
b=5
try:
if a/b > 4:
print(a/b)
else:
print((a+b)//2)
except:
print("Error in code ")
Or
(B) (i) When is KeyError exception raised.
(ii) When is IOError exception raised.
Ans:- 4. A) (i) The except clause houses code that will catch the exceptions and execute
proper exception handling code, if an exception occurs.
(ii) IndentationError
Or
(B) (i) KeyError is raised when the key to be accessed is not found in the dictionary.
(ii) IOError exception occurs if Input/Output operation fails.