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:
System.Diagnostics.Debugger.Launch();
on line 1 of Main()
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?
That's weird indeed. I verified the problem also exists with VB.Net so it's not a C# specific issue. It will need to be confirmed by the core debugger team but it does look like a bug.
Please file a bug on Connect and post the bug number as a comment to my OP so that I can make sure it gets routed to the correct team.
This is a known issue that is caused by a bug in the CLR. It has been fixed in CLR 4.0 (as yet unreleased).
Thanks to JaredPar for the assistance with this. See comments on his answer for more detail and link to the original bug report on Microsoft Connect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With