Catching exceptions
Before you start writing your own custom exceptions, let's make sure you have the fundamentals of handling exceptions down.
In this exercise, you are given a function invert_at_index(x, ind)
that takes two arguments, a list x
and an index ind
, and inverts the element of the list at that index. For example invert_at_index([5,6,7], 0)
returns 1/5
, or 0.2
.
Your goal is to implement error-handling to raise custom exceptions based on the type of error that occurs.
This exercise is part of the course
Introduction to Object-Oriented Programming in Python
Exercise instructions
Use a try
- except
- except
pattern (with two except
blocks) inside the function to catch and handle two exceptions as follows:
try
executing the code as-is, returning1/x[ind]
.- if
ZeroDivisionError
occurs, print"Cannot divide by zero!"
, - if
IndexError
occurs, print"Index out of range!"
You know you got it right if the code runs without errors, and the output in the console is:
0.16666666666666666
Cannot divide by zero!
None
Index out of range!
None
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Modify the function to catch exceptions
def invert_at_index(x, ind):
____:
return 1/x[ind]
_____:
print("____")
____:
print("____")
a_list = [5,6,0,7]
# Works okay
print(invert_at_index(a_list, 1))
# Potential ZeroDivisionError
print(invert_at_index(a_list, 2))
# Potential IndexError
print(invert_at_index(a_list, 5))