Search code examples
c#genericstry-catchcircuit-breaker

Why can I write a generic catch statement in C# that does nothing?


Possible Duplicate:
Why can’t I catch a generic exception in C#?

I have been reviewing and writing Circuit Breaker code recently. The following method compiles, but the catch block is never entered. I have plenty of work-arounds, and this isn't the only way to get the right behavior (filtering exceptions), but I'm curious why this compiles and doesn't work!

public void AttemptCall<TException>(Action action) 
    where TException : Exception
{
    try
    {
        action();
    }
    catch(TException e)  // This block is never entered!
    {
         state.ActUponException(e);
         throw;
    }
}

Here is a test that should enter the catch block of the previous method.

[TestMethod]
public void Throw_an_exception()
{
    circuitBreaker.AttemptCall<Exception>(() => throw new Exception());
    // test the circuit breaker's state
}

Solution

  • Its a bug https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0