Can anyone explain the "finally" concept in programming? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can anyone explain the "finally" concept in programming?

I doesn't understand the concept of "finally" In the Python . Even the comments are also I can't understand. Explain elaborately.

15th May 2019, 6:45 AM
Hari Krishna Sahu
Hari Krishna Sahu - avatar
5 Answers
+ 12
Cracker is right. I would add that finally will execute even if "return" is met: def test(x,y): try: res = x/y except: return ("mmmh, we had a problem") finally: print("I will always be printed") return res print(test(3,2)) print(test(3,0))
15th May 2019, 8:32 AM
Cépagrave
Cépagrave - avatar
+ 5
Side note: Because finally blocks are executed in any case, you can use them to clean up your code even if there's an exception: try: f = open('file.dat', 'wt') f.write(5/0) except ZeroDivisionError: print('Can\'t divide by 0') finally: f.close() print('file was closed') Without the "finally" statement, a ZeroDivisionError would be raised and the program would be terminated without explicitly closing the file that was previously opened. The finally statement makes sure that the file is closed in any case (which is important to allow other processes to access the file).
15th May 2019, 8:32 AM
Anna
Anna - avatar
+ 4
The finally block will be executed no matter if the try block raises an error or not. consider this example, try:   x > 3 except:   print("Error!") finally:   print("The try-except block is completed") # The finally clause will always execute after the try-except clause!
15th May 2019, 7:06 AM
Cracker
Cracker - avatar
+ 2
It's an extension of the try-catch block It executes compulsorily It's usually used for garbage collection 😎
15th May 2019, 2:27 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
Finally block is used to run commands that must be executed whether your programme run successfully or not for example backup commands and close database connection it enhance the security and performance
21st Jul 2019, 5:46 PM
Krishan
Krishan - avatar