Why we use expect and finally function in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why we use expect and finally function in python?

26th Jul 2020, 11:44 AM
LOKESH CHAUHAN
LOKESH CHAUHAN - avatar
2 Answers
+ 2
except is used to stop errors from terminating the program and to run a block of code instead. This is useful when some errors are unnecessarily hard to prevent. finally is used to make a block of code be ran no matter what. You could think about an IDE program, if an unexpected error appears, the app would crash and the user would lose unsaved work, but if there was a finally block to automatically save the code, every thing would be good.
26th Jul 2020, 12:01 PM
Seb TheS
Seb TheS - avatar
+ 2
I think you mean except ? It's for catching error and doing something and finally is used in case some error occurs the statements in finally will still be executed ,unlike when error occurs in program the rest of code isn't executed , You can consider opening of file by user try: f=open("filename","open-mode") for i in f: print(i) except IndentationError: Do something finally: f.close() now in the above example if an error occurs like you can see there is indentationError ,file will still be closed
26th Jul 2020, 12:02 PM
Abhay
Abhay - avatar