Exception Handling - Worksheet - Answer Key
Exception Handling - Worksheet - Answer Key
Answer Key
18. c) Exception
19. a) No Error
20. c) Index Error
21. b) Name Error
22. d) Type Error
23. d) Bye (printed infinite number of times)
24. c) Assignment Error
25. a) an object
26. d) IOError
27. a) Indentation Error
28. b) locals()
print(dir(locals()['__builtins__']))
# Above code returns all the builtin exceptions in Python in the form of list
29. c) Index Error
30. b) Identifiers
31. b) only one
32. a) ValueError
33. a) Python!
34. except, finally
35. #Program to raise ValueError exception
try:
n=int(input("Enter an integer:"))
except ValueError:
print("ValueError:Invalid literal for int()")
else:
print("Entered value is a valid integer")
finally:
print("Task over")
36. #Program to raise IndexError exception
L=[12,34,65,45,23]
print(L)
try:
n=int(input("Enter the index position of element you want to delete:"))
L.pop(n)
except IndexError:
print("IndexError:List index out of range")
else:
print("New List is",L)
finally:
print("Task over")
37. #Program to handle ArithmeticError exception
n1,n2=eval(input("Enter the dividend and divisor:"))
try:
Q=n1/n2
except ArithmeticError as AE:
print(AE,” Divisor can’t be zero”)
else:
print("Quotient is",Q)
finally:
print("Task over")
38. #Program to handle ZeroDivisionError exception
def divide(a,b):
try:
c=a/b
except ZeroDivisionError:
print("ZeroDivisionError:Divisor can't be zero")
else:
print("Quotient is",c)
finally:
print("Task over")
divide(12,5)
divide(4,0)
39. print (" Learning Exceptions...")
try:
num1= int(input ("Enter the first number"))
num2=int(input("Enter the second number"))
quotient=(num1/num2)
print ("Both the numbers entered were correct")
except ValueError: # to enter only integers
print (" Please enter only numbers")
except ZeroDivisionError: # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
finally: # to be executed at the end
print(" JOB OVER... GO GET SOME REST")
40. ArithmeticError:
It is an error occurs while performing mathematical operations or when
arithmetic operation fails to produce the result.
Types:
i) OverFlowError
ii) ZeroDivisionError
iii) FloatingPointError