+ 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?

26th Jan 2018, 7:20 AM
Boris Stricky
Boris Stricky - avatar
7 Réponses
+ 3
finally statement gets executed at the end of the program irrespective of errors.
26th Jan 2018, 7:23 AM
‎ ‏‏‎Anonymous Guy
+ 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
26th Jan 2018, 7:41 AM
Sunil Thakali
Sunil Thakali - avatar
+ 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
26th Jan 2018, 11:43 AM
Sunil Thakali
Sunil Thakali - avatar
+ 1
As a minor side note, it is used at the end of a try/catch block, not necessarily the end of a program :)
26th Jan 2018, 7:44 AM
Dan Walker
Dan Walker - avatar
+ 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?
26th Jan 2018, 7:48 AM
Boris Stricky
Boris Stricky - avatar
+ 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?
26th Jan 2018, 12:39 PM
Dan Walker
Dan Walker - avatar