When programming, errors happen. It's just a fact of life. Perhaps the user gave bad input. Maybe a network resource was unavailable. Maybe the program ran out of memory. Or the programmer may have even made a mistake!
Python's solution to errors are exceptions. You might have seen an exception before.
# this will return an error
print(a)
But sometimes you don't want exceptions to completely stop the program. You might want to do something special when an exception is raised. This is done in a try/except
block.
Here's a trivial example: Suppose you're iterating over a list. You need to iterate over 20 numbers, but the list is made from user input, and might not have 20 numbers in it. After you reach the end of the list, you just want the rest of the numbers to be interpreted as a 0. Consider the example below.
def do_stuff_with_number(n):
print(n)
def catch_this():
the_list = (1, 2, 3, 4, 5)
for i in range(20):
try:
do_stuff_with_number(the_list[i])
except IndexError: # Raised when accessing a non-existing index of a list
do_stuff_with_number(0)
catch_this()
Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong.")
Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("This is the final statement")
Exercise
Handle all the exceptions. The actor's last name should be returned.
# Setup
actor = {"name": "John Cleese", "rank": "awesome"}
# Function to modify!!!
def get_last_name():
return actor["last_name"]
# Test code
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())
actor = {"name": "Jeremy Irons", "rank": "awesome"}
def get_last_name():
return actor["name"].split()[1]
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())
test_output_contains("All exceptions caught! Good job!")
test_output_contains("The actor's last name is Irons")
success_msg("Excellent")