5️⃣

19.5 Finally

Finally

The finally statement is used when you want a chunk of code to run whether or not the try section creates an error. Basically, it’s something you always want to run. To use it, just type finally: and remember to indent the next line. It should be placed beneath all try, except, and else keywords in the clause.

try:
	x = 1
	y = "hi"
	x + y
except:
	print("something went wrong")
else:
	print("no errors found")
finally:
	print("x is", x, "\ny is", y) #will run no matter what

View code on GitHub.

Practice

Finally Use

Write a function that takes two parameters. It should try to divide parameter 1 by parameter 2 to get a result. The function should then attempt to print that result. However, if something goes wrong, print a message, saying, “something went wrong”. Finally, it should, no matter what, print “Goodbye World” when it is done. (Optional: have specific messages for different errors).

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.