If we can close by the close method, then what's the necessity of using finally? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

If we can close by the close method, then what's the necessity of using finally?

31st Mar 2016, 4:37 AM
Bne Ayoub
Bne Ayoub - avatar
2 Answers
+ 4
Hi, I believe in the example they showed where there is a simple file operation it doesn't make sense to do it finally. But say when you have a lot of file operations that you have done after a lot of lines of code in the try block, the finally will ensure no matter what you have done the file will be closed.
1st Apr 2016, 11:09 AM
Naveen Menon
Naveen Menon - avatar
+ 4
if an error occurs before the close method then the file is not closed. Using finally ensures that the file is closed even if there is an error
14th Apr 2016, 8:47 PM
jam
jam - avatar