Advertisement



< Prev
Next >



C# Finally Block










Conditions when a finally block runs -



Therefore, 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


using System;
using System.IO;

class FinallyEx
{

public static void Main(String[] ar)
{
	FileStream f = null;
	try
	{
		//Creating a file stream  
		f = new FileStream("E:\\File.txt", FileMode.OpenOrCreate);

		//writing a byte to the stream  
        	f.WriteByte(65);

		//Flushing the data to a file
		f.Flush();				
	}
	catch(IOException e)
	{
		Console.WriteLine("Exception caught: " + e);
	}		
	finally
	{
		try
		{
			//Cleaning up the resources i.e. closing an opened file.
			f.Close();		
		}
		catch(IOException e)
		{
			Console.WriteLine(e);
		}
	}	
}		
}

This program creates a text file named File.txt in E drive and writes a byte to it. The finally block runs the clean-up code i.e. by calling the Close() method to close the opened stream, after the data is flushed to the file.



Please share this article -





< Prev
Next >
< C# Nested Try Catch
C# Throw Keyword >



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