Menu
Coddy logo textTech

Finally

Lesson 5 of 16 in Coddy's Exception Handling in Python course.

There is another optional block which is called finally.

This block is executed under all circumstances. This block runs whether or not the try statement produces an Exception.

try:
	f = open("data.txt",encoding='utf-8')
except FileNotFoundError:
	print("File does not exist")
else:
	print(f.read())
finally:
	print("cleanup activities like closing file")	

In above example, Exception will be raised if data.txt doesn't exist and except block will be executed.

If file exists, control goes to else block because of no exception and interpreter will read the data. 

Finally block is executed in both cases which will perform cleanup activities, mandatory code, system operations, releasing memory etc

challenge icon

Challenge

Easy

Write a function to add new key-value pairs into given dictionary. Handle TypeError when user enters mutable keys i.e list and print "Cannot give mutable keys". If key-value added successfully, then print added value for new key. Finally, print a dictionary after operation is done. 

Try it yourself

data = {
    'John' : 89,
    'Mike' : 91,
    'Angela':85,
}
def insert_data(key,value):
    #add key-value in data
    #Handle TypeError if mutable key i.e list
    #print updated dictionary after operation is done

All lessons in Exception Handling in Python