finallystatement 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
elsekeywords 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.
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).