Sunday, February 15, 2009

Exceptions - Part1


Consider the following code :

public static void Main()
{
try
{
Inner();
}
catch (Exception e)
{
Console.WriteLine("Main Catch");
}
finally
{
Console.WriteLine("Main finally");
}
}
private static void Inner()
{
try
{
StillInner();
}
finally
{
Console.WriteLine("Inner finally");
}
}
private static void StillInner()
{
try
{
Console.WriteLine("Throwing from StillInner");
throw new Exception("StillInner");
}
finally
{
Console.WriteLine("StillInner finally");
}
}

The output is as follows :

Throwing from StillInner
StillInner finally
Inner finally
Main Catch
Main finally

As you can see, catch block was searched in the call stack, and all finally’s leading to it were executed before the catch could be executed and finally the catching finally was executed.

What if Main did not have the required catch type? Then the output is as follows :

Throwing from StillInner

Unhandled Exception: System.Exception: StillInner
at ConsoleApplication1.MainClass.StillInner() in …
at ConsoleApplication1.MainClass.Inner() in …
at ConsoleApplication1.MainClass.Main() in …

StillInner finally
Inner finally
Main finally

So, basically, finally will always get executed even if there is no catching block.
The only situation in which finally does not get executed is when the stack overflows.

When stack overflows, nothing is executed and you get the following message :

Process is terminated due to StackOverflowException.

Even if you have the StackOverflowException handler, it is not executed.

There is one more situation, assume, the StillInner Class throws exception in the finally block itself, then? Then it is treated as if the exception was generated outside the finally and a search for the catchtype is initiated, if it is found in Main, then you get the following output :

Throwing exception from StillInner Finally
Main Catch
Main finally
After Main try catch finally


What you see is that it only executed the Main’s finally not the Inner Finally, also after executing finally, main continued execution till it finished.

No comments: