+ 1
What is the use of finally statement?
if finally statement is used whatever happens in the try: block, why do we need it? can we just write this line of code outside the block?
7 Antworten
+ 3
finally statement gets executed at the end of the program irrespective of errors.
+ 2
one example of using finally would be using it while closing a file.so that after we use the file for different purpose..it make sure that the file is being closed after operation to prevent the leakage of resources..finally{ f.close();} is sure way to keep the file close after the use..That means finally is used when we want to make sure it is executed( even if exception occurs and terminates the program) statement within finally block will be executed before closing a program.I hope that helps to get general idea
+ 2
@Boris I do not know much about python and I do not know how the code you wrote works..can you clearify..it is always good to know alternative ways..it seems you are reading the file inputs line by line..And you can always find more about the use of finally in the internet.Thanks
+ 1
As a minor side note, it is used at the end of a try/catch block, not necessarily the end of a program :)
+ 1
@Sunil:
wouldn't making sure a file is closed be better done with "with" statement?
with open("file.csv","w") as file:
line = file.readline()
line/0
wouldn't this code already close the file no matter what, even an exception?
+ 1
@Sunil @Boris it's kind of like a try-with-resources in Java 7, in case that helps. While it is a neater way of handling closeable streams it doesn't use finally, and of course that is required pre-java 7. Don't know if Python has a similar difference in its versions?