I wrote a simple C # console application:
class Mystery
{
static void Main(string[] args)
{
MakeMess();
}
private static void MakeMess()
{
try
{
System.Console.WriteLine("try");
throw new Exception();
}
catch(Exception)
{
System.Console.WriteLine("catch");
throw new Exception("A");
}
finally
{
System.Console.WriteLine("finally");
throw new Exception("B");
}
}
}
The output indicated in the console:
to try
catch
Unhandled exception: System.Exception: A in Mystery.Program.MakeMess () in ...
It seems that the CLR caught A , and the finally block was not called at all.
But when I surround the MakeMess () call with a try-catch block:
static void Main(string[] args)
{
try
{
MakeMess();
}
catch(Exception ex)
{
System.Console.WriteLine("Main caught " + ex.Message);
}
}
The output looks completely different:
to try
catch
finally,
The main caught B
It seems that the exception propagating from MakeMess () is different when the Exception is strictly handled outside the method.
What is the explanation for this behavior?
source
share