10

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
}
Community
  • 1
  • 1
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
  • I don't see anything wrong with the code you posted. perhaps something strange is going on inside of state.ActUponException(e). – Jimmy Jan 08 '10 at 18:18
  • It should either not compile and disallow using a generic type as the catch filter OR compile and have the runtime exception caught and handled properly. The fact that it compiles but then doesn't catch the exception is odd. – Samuel Neff Jan 08 '10 at 18:20
  • @Jimmy, try to run the code it doesn't do what you expect it to do. – Stan R. Jan 08 '10 at 18:20
  • 1
    @Anthony..this is duplicate http://stackoverflow.com/questions/1577760/why-cant-i-catch-a-generic-exception-in-c – Stan R. Jan 08 '10 at 18:28
  • I did search before posting... there are so many choices how to word this problem, I can see how it happened. – Anthony Mastrean Jan 08 '10 at 20:22

1 Answers1

5

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

Stan R.
  • 15,757
  • 4
  • 50
  • 58