为什么我可以在 C# 中编写一个不执行任何操作的通用 catch 语句?
可能的重复:
为什么我无法捕获 C# 中的通用异常?
我一直在审查和撰写断路器 最近编写代码。以下方法可以编译,但不会进入 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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个错误 https://connect.microsoft .com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0
Its a bug https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0