Why can I write a generic catch statement in C# that does nothing? [duplicate]
Asked Answered
L

1

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
}
Landgravine answered 8/1, 2010 at 18:10 Comment(5)
I don't see anything wrong with the code you posted. perhaps something strange is going on inside of state.ActUponException(e).Mettah
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.Athamas
@Jimmy, try to run the code it doesn't do what you expect it to do.Abeyta
@Anthony..this is duplicate #1578260Abeyta
I did search before posting... there are so many choices how to word this problem, I can see how it happened.Landgravine

© 2022 - 2024 — McMap. All rights reserved.