< Prev
Next >

Python - Finally Block

Conditions when a finally block runs :

So, a finally block(when defined) always runs, no matter if an exception is thrown or not.

Use of finally block

Objects may hold references to the system resources like memory, files, a database which need to be released in a timely fashion when they are no longer needed. Hence, a finally block usually contains a clean-up code i.e. code to release any of such resources that were referenced or locked in the try block or the code which will not be raising any exception at all.

Example of a finally block

# Python - finally block example

#Declaring a variable named File with None keyword to temporarily not give it a value
file = None

	file = open('D:\File.txt','w');			#creating a file
	file.write('Hello from Python')			#writing data to a file
	file.flush()                                    #flushes the data to a file

except Exception as e :
	print("An exception is caught :", e)

finally :
	file.close()		                #cleaning up the resources i.e. closing an opened file.

This program creates a text file named "File" in D drive and writes a string Hello from Python to it. Here we have used finally block to run the clean-up code i.e. by calling the close() function to close the stream after the data is flushed to the file.

Please share this article -

< Prev
Next >
< Python try, except, else block
Python raise keyword >


Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition