Wednesday, December 1, 2010

Finally Block

How to work with finally?
Finally block guarantees to execute in each and every condition whether it is successful completion of a function or any error has been occurred not matter finally block would execute definitely.But control should come in try block if it did not come in try block and return before try block than finally will not execute.

Example 1

private void Show()
{
try
{
Console.Writeline("In try");
return;
}
catch(Exception ex)
{
throw ex;
}

finally
{
Console.Writeline("Finally");
}
}

Output :- In try Finally
Example 2

private void Show()
{
Console.Writeline("In Function");
try
{
Console.Writeline("In try");
return;
}

catch(Exception ex)
{
throw ex;
}

finally
{
Console.Writeline("Finally");
}
}

Output :- In Function In try Finally

Finally block used for to close any open file or connection or to null the reference type variables or for all type of work that you want to do in each and every condition.

There is some limitation of finally block you can not write return statement there since there is a chance that it may override the actual return statement.

If you write return statement there it will throw a compile time error.

"Control cannot leave the body of a finally clause."

Even you can not modify the return value inside finally block. Though it will not give any error but will not affect output.Since return value already decided before it goes to finally block,

public class ReturnExample
{
private String normalExecution()
{
String result = "";
try
{
result = "Entered try block.";
return result;
}

catch(Exception e)
{
result = result + "Entered Catch block.";
return result;
}

finally
{
result = result + "Entered finally block.";
}
}

public static void main(String[] args)
{
ReturnExample example = new ReturnExample();
String result = example.normalExecution();
Console.Writeline(result);
}

Output :- Entered Try block.


Finally block is not like if or for means in case of if or for there is no need of braces if we have only one line but same is not true for finally. Braces are compulsory for finally.Although you can write only try and catch or try and finally.

These are all correct
try
{
}
catch
{
}

or
try
{
}
finally
{
}

No comments:

Followers

Link