Monday, February 1, 2010

Explain how to use the finally statement

Explain how to use the finally statement by providing sample code using C#.NET.

Finally statement is executed always irrespective of any condition or error occurring in a method. It is often used to cleanup code.
E.g.:
public void MyMethod()
{
      try
      {
              //code to connect to database
              //code to perform action
       }
       catch (Exception ex)
        {
             //handle exception
        }
        finally
        {
                    //code to disconnect database.
        }
}

0 Comments: