Week 10- In Class Activity
Exception Handling
Section A:
Q01:
a) Define exceptions in Python. Explain why they are important in programming.
[2 marks]
b) List any three common exceptions in Python and explain when they occur.
[3 marks]
Section B:
Read each code segment carefully and identify the type of exception it will raise.
Also, briefly explain the reason for the exception.
Q02:
num = int("ten")
a) What is the exception?
[1 mark]
b) Why does this occur?
[1 mark]
Q03:
my_list = [1, 2, 3]
print(my_list[5])
a) What is the exception?
[1 mark]
b) Why does this occur?
[1 mark]
Q04:
value = 5 / 0
a) What is the exception?
[1 mark]
b) Why does this occur?
[1 mark]
Q05:
d = {"a": 1, "b": 2}
print(d["c"])
a) What is the exception?
[1 mark]
b) Why does this occur?
[1 mark]
Section C:
Complete the following Python code snippets by filling in the blanks to handle
exceptions properly.
Q06:
try:
result = 10 / 0
except ____________:
print("You cannot divide by zero.")
Q07:
try:
num = int("abc")
except ____________:
print("Invalid number format.")
Q08:
Assume you do not have the [Link] file inside the same folder that you have
saved the python file.
try:
f = open("[Link]", "r")
content = [Link]()
except ____________:
print("File not found.")
Section D:
Write the output of each of the following code snippets. If an error occurs, state the
exception and explain briefly.
Q09:
try:
x = int("5")
y = 10 / x
print("Result:", y)
except ZeroDivisionError:
print("Cannot divide by zero.")
Q10:
try:
my_list = [1, 2, 3]
print(my_list[3])
except IndexError as e:
print("Index error occurred:", e)
Q11:
try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("Key not found in dictionary.")
Q12:
try:
print("Hello")
finally:
print("End of program")