C# – Finally Block

Finally block:

  • Finally, block is used to close resources (file, database etc.) after use.
  • Finally block executes whether or not an exception raised.
using System;				
public class Program
{
	public static void Main(string[] args)
	{
		try
		{
			int a=10, b=0;
			int c=a/b;
			Console.WriteLine("Try block");
		}
		catch (Exception)
		{
			Console.WriteLine("Catch block");
		}
		finally
		{
			Console.WriteLine("Finally block");
		}
	}
}

Why closing statements belongs to finally block?

  • Resource releasing logic must be executed whether or not an exception raised.
  • For example, in ATM Transaction – the machine should release the ATM card in success case or failure case.

Open and close the file using finally block:

using System;
using System.IO;
public class Program 
{
	public static void Main(string[] args) 
	{
		StreamReader sr = null;
		try 
		{
			sr = new StreamReader("d:/new.txt");
			string line;
			while ((line = sr.ReadLine()) != null) 
			{
				Console.WriteLine(line);
			}
		} 
		catch (Exception) 
		{
			Console.WriteLine("Exception : No such file");
		}
		finally
		{
			if(sr != null)
			{
				sr.Close();
				Console.WriteLine("File closed");
			}
		}
	}
}
Scroll to Top