What is the main use of a finally block in exception handling ?

 Posted by Bharathi Cherukuri on 7/25/2012 | Category: ASP.NET Interview questions | Views: 2676 | Points: 40
Answer:

Finally block is always followed by the Try block.
This is because, it is used to free the resources that are used in the try block.

Example:

using System;
using System.IO;

class FinallyDemo
{
static void Main(string[] args)
{
FileStream outStream = null;
FileStream inStream = null;

try
{
outStream = File.OpenWrite("DestinationFile.txt");
inStream = File.OpenRead("BogusInputFile.txt");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (outStream != null)
{
outStream.Close();
Console.WriteLine("outStream closed.");
}
if (inStream != null)
{
inStream.Close();
Console.WriteLine("inStream closed.");
}
}
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Bhupentiwari on: 7/27/2012 | Points: 10
try

{
code which can produce error
}
catch()
{
handle that error generated by try block
}
finally
{
a code which is going to executes in spite of whether error is generated in try block or not
}


you can use finally block to close the connection to databases,files n etc.

Login to post response