Pages

Wednesday, May 22, 2013

finally block and its advantage in c#

Finally block is a block in which code will be always executed even in presence of return statement.
->CLR guarantee the execution of the finally block.
->Code in finally blocks is always executed .Finally provides a construct for ensuring the correct execution of programs. It ensures a block of statements are always reached before the enclosing method is exited .
->It is use in SQL connection ,sql connection should be closed in finally block

Sample code:

Public class Test
{
protected void page-load(-,-)
  {
    A a=new A();
    a.div(10,0);      //exception
   }
}
public class A
  {
    public div(int x,int y)
    {
      try
      {
       int z=x/y;
      return z;
     }
   catch(exception ex)
  {
   finally
     {
       int k=30;
     }
  }
}
Note:
Exception is a conditional that is caused by a run time error in the program. When C# compiler encounters an error such as dividing an integer by zero, it creates an exception object and throws it. If the exception object is not caught and handled properly the compiler will display an error message and will terminate the program

No comments:

Post a Comment