Pages

Wednesday, 22 July 2015

finally Block

The finally Block

If a program's flow of control enters a try statement that has a finally block, the finally block is always executed, like following figure:

  • If no exception occurs inside the try block, then at the end of the try block, control skips over any catch clauses and goes to the finally block.
  • If an exception occurs inside the try block, then the appropriate catch clause in the catch clauses section is executed, followed by execution of the finally block.
The finally block will always be executed before returning to the calling code, even if a try block has a return statement or an exception is thrown in the catch block. For example, in the following code, there is a return statement in the middle of the try block that is executed under certain conditions. This does not allow it to bypass the finally statement.
static void Main(string[] args)
{
 int inVal = 5;
 try
 {
  if (inVal < 10)
  {
   Console.Write("First Branch - ");
   return;
  }
  else
   Console.Write("Second Branch - ");
 }
 finally
 { 
  Console.WriteLine("In finally statement");
 } 
}

The code will display:
First Branch - In finally statement

0 comments:

Post a Comment