Advertisement



< Prev
Next >



Java - 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, 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.




Example of a finally block


//Java - Finally Block


import java.io.*;

public class Finally
{

public static void main(String... ar)
{

FileWriter fileWriter = null;
try
{
	File file = new File("D:\\File.txt");
	fileWriter = new FileWriter(file);		//creating a file
	fileWriter.write("Hello Java");			//writing data to a file
	fileWriter.flush();				//flushes the data to a file
}		//try block ends

catch(IOException e)
{
	e.printStackTrace();
}		//catch block ends

finally
{
	try
	{
		fileWriter.close();		//cleaning up the resources i.e. closing an opened file.
	}
	catch(IOException e)
	{
		System.out.println(e);
	}
}		//finally block ends

}		
}		

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



Please share this article -





< Prev
Next >
< Try Catch Block
Multiple Catch Blocks >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement