2010-01-08 83 views
10

可能重複:
Why can’t I catch a generic exception in C#?爲什麼我可以在C#中編寫一個通用的catch語句,該語句什麼都不做?

我一直在檢討和最近寫Circuit Breaker代碼。以下方法編譯,但catch塊永遠不會被輸入。我有很多解決方法,這不是獲得正確行爲(過濾例外)的唯一方法,但我很好奇爲什麼這個編譯和不工作

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

下面是應該進入前一種方法的catch塊測試。

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

我看不出什麼毛病,你發佈的代碼。或許是一些奇怪的事情發生在state.ActUponException(e)中。 – Jimmy 2010-01-08 18:18:38

+0

+ 1 ..好問題。 – 2010-01-08 18:19:02

+0

它應該不編譯和不允許使用泛型類型作爲捕獲過濾器或編譯並且捕獲並正確處理運行時異常。它編譯的事實,但沒有抓住例外是奇怪的。 – 2010-01-08 18:20:10

回答