Consider the console application below, featuring a method with a generic catch handler that catches exceptions of type TException
.
When this console application is built with the 'Debug' configuration and executed under the Visual Studio debugger (i.e. through the *.vshost.exe) this fails, in both Visual Studio 2005 and Visual Studio 2008.
I believe this problem only came about after I installed Visual Stuido 2008.
using System;
class Program
{
static void Main()
{
Console.WriteLine(Environment.Version);
CatchAnException<TestException>();
Console.ReadKey();
}
private static void CatchAnException<TException>()
where TException : Exception
{
Console.WriteLine("Trying to catch a <{0}>...", typeof(TException).Name);
try
{
throw new TestException();
}
catch (TException ex)
{
Console.WriteLine("*** PASS! ***");
}
catch (Exception ex)
{
Console.WriteLine("Caught <{0}> in 'catch (Exception ex)' handler.", ex.GetType().Name);
Console.WriteLine("*** FAIL! ***");
}
Console.WriteLine();
}
}
internal class TestException : Exception
{
}
Under the following circumstances the code behaves as expected:
- If built with 'Release' configuration, it succeeds.
- If executed via the *.exe directly, rather than through Visual Studio (F5), it succeeds.
- If attaching a debugger by putting
System.Diagnostics.Debugger.Launch();
on line 1 ofMain()
it still succeeds.
When the console application is launched from within Visual Studio (2005 or 2008), and therefore executed under ConsoleApplication.vshost.exe, it fails.
Here is my output for the failure case
2.0.50727.3068
Trying to catch a <TestException>...
*** FAIL! ***
Caught <TestException> in 'catch (Exception ex)' handler.
Expected: <TestException>
Actual: <TestException>
Result of typeof(TException) == ex.GetType() is True
What is causing this peculiar failure?