Exception propogation question

A

Adam Clauss

Consider the following code:

try
{
methodA();

try
{
methodB();
}
finally
{
methodC();
}
}
catch (Exception e)
{
//some sort of error handling
}

If methodA completes successfully, and methodB throws an exception, methodC
would then be called before the catch statement correct?

What happens if methodC then throws an exception? Which of those exceptions
get's handled in the catch? Is the other exception 'lost'?
 
D

Dave Sexton

Hi Adam,

A simple test reveals that the exception thrown by MethodC replaces the
previous exception thrown by MethodB, and its the MethodC exception that is
caught by the outer try...catch block:

static void Main(string[] args)
{
try
{
MethodA();

try
{
MethodB();
}
finally
{
MethodC();
}
}
catch (Exception ex)
{
Console.WriteLine("Catch: " + ex.Message);
}
}

static void MethodA()
{
Console.WriteLine("MethodA");
}

static void MethodB()
{
Console.WriteLine("MethodB");
throw new Exception("Exception from MethodB");
}

static void MethodC()
{
Console.WriteLine("MethodC");
throw new Exception("Exception from MethodC");
}

Result:

MethodA
MethodB
MethodC
Catch: Exception from MethodC
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top