Related to finally

finally block is useful for writing cleanup codes(like closing a file). But my question is, what if a file doesn’t exist and we are reading it in a try block, so finally block will also throw an error that such file doesn’t exist that you are trying to close.
try:
file = open(‘data.txt’)
except:
print(‘error’)
finally:
file.close()
Suppose, data.txt doesn’t exist, so is it a good practice to write cleanup codes in finally block?

hey @Mohit2000 ,
But think too naaa , when you don’t have any such file , why you will close it.
You are corect that we write cleanup codes in finally block , but we also need to that are those cleanup codes that will work always and will doesn’t get into any such error.

I hope this helps.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.