问题描述
我在做的code一些单元测试可能会抛出一些根据输入异常。所以,我想是这样的低于code:(简化的例子)
I was doing some unit testing on code that could throw a number of exceptions depending on the inputs. So I tried something like the below code: (simplified for the example)
static void Main(string[] args)
{
RunTest<ArgumentException>();
}
static void RunTest<T>() where T : Exception, new()
{
try
{
throw new T();
//throw new ArgumentException(); <-- Doesn't work either
}
catch (T tex)
{
Console.WriteLine("Caught passed in exception type");
}
catch (Exception ex)
{
Console.WriteLine("Caught general exception");
}
Console.Read();
}
但是,这总是会打印出中招一般例外中,抓(T TEX)的处理程序将不会工作。这不要紧,无论我把T()或明确地抛出ArgumentException的()。任何想法,这是为什么?其实我是那种惊讶的是,我甚至能够使用T中的catch子句中,但因为这是可能不应该这样的工作?或者至少给出一个编译器警告/错误,指出该处理器将永远不会工作?
But this will always print out "Caught general exception", the catch(T tex) handler will never work. It doesn't matter whether I throw T() or explicitly throw ArgumentException(). Any ideas why this is? Actually I was kind of surprised that I was even able to use T in the catch clause, but since that's possible shouldn't this work? Or at least give a compiler warning/error that says that this handler will never work?
我的环境是Visual Studio 2008和3.5的目标框架。
My environment is Visual Studio 2008 and 3.5 is the target framework.
更新:我在命令提示符下试了一下,现在直接,然后打印出夹缝传递异常类型。因此,它看起来像这样被限制在Visual Studio中运行。也许在Visual Studio宿主进程的特点?
UPDATE: I tried it now directly from the command prompt and then it prints out "Caught passed in exception type". So it looks like this is restricted to running from within Visual Studio. Maybe a peculiarity of the Visual Studio hosting process?
推荐答案
在这里怪异的行为...
Bizarre behavior here...
VS2k8控制台应用程序。以下内容:
VS2k8 console app. The following:
try
{
throw new T();
}
catch (T tex)
{
Console.WriteLine("Caught passed in exception type");
}
catch (Exception ex)
{
Console.WriteLine("Caught general exception");
}
结果中招一般例外
不过,从catch语句删除(无用)变量:
But, remove the (useless) variables from the catch statements:
try
{
throw new T();
}
catch (T)
{
Console.WriteLine("Caught passed in exception type");
}
catch (Exception)
{
Console.WriteLine("Caught general exception");
}
结果夹缝中的异常类型通过!
更新
Heheh ......它是一个错误:<一href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0
Heheh... Its a bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0
来源?这里。 http://stackoverflow.com/questions/700935/why-does-catchtexception-handling-block-behaviour-differ-under-the-debugger-aft
这篇关于为什么我不能赶在C#泛型例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!