Order of Try Catch Finally execution between methods
December 26, 2010 Leave a Comment
This post is to understand how does an exception propagates through a method stack. Consider the following code:
static void Main(string[] args)
{
var testObject = new Test4TryCatch();
testObject.M1();
}
public void M1()
{
try
{
Console.WriteLine("Line in M1 before calling M2");
M2();
Console.WriteLine("Line in M1 after callig M2 and after exception");
}
catch (Exception e)
{
throw new Exception("Exception in M1", e);
}
finally
{
Console.WriteLine("Line in M1 finally");
}
}
public void M2()
{
try
{
Console.WriteLine("Line in M2 before exception");
throw new Exception("Explicit exception for M2 try block");
Console.WriteLine("Line in M2 after exception");
}
catch (Exception)
{
throw;
}
finally
{
Console.WriteLine("Line in M2 finally");
}
}
In the above written snippet, following would be the order of execution upon calling M1 from Main:
1. M1′s first line – “Line in M1 before calling M2″ would output
2. M2′s first line – “Line in M2 before exception” would output
3. An exception with message “Explicit exception for M2 try block” would be thrown from M2′s try block
4. Same exception re-thrown by M2′s catch block
5. M2′s finally block gets executed – “Line in M2 finally”
6. The controls passes to M1′s catch block which hides the M2 exception by creating a new exception with message “Exception in M1″ as well as an inner exception containing the M2 exception object (e).
7. Ultimately, M1′s finally block gets executed – “Line in M1 finally”.
The important points to remember are:
1. Finally of all methods would be executed
2. Exception thrown can be different from what actually occurred as it depends on the outermost catch block’s handling behavior.