Wednesday, August 24, 2011

Why do we need Try-Finally block


The output that the code in the finally block will be executed after throwing the exception. However, the last statements in the program that followed the finally block will not be executed. This means that the exception
prevents control from being transferred to any part of the program except the finally block.



using System;
public class MyClass
{
static void Main()

{
string myString = "Finally";
object myObject = myString;
try
{
// The following conversion is invalid.
// It throws an exception.
int myInt = (int)myObject;
}
finally
{
// The code in this block is always executed:
Console.WriteLine("The program continues and ends here:");
Console.WriteLine("My String is: {0}", myString);
}
// The following code will not be executed:
Console.WriteLine("Hello again!");
}
}

It is also used for cleaning up the resource, like to close the open file stream..

No comments:

Post a Comment