我正在对代码进行一些单元测试,这些代码可能会根据输入抛出许多异常。所以我尝试了类似下面的代码:(针对示例进行了简化)
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() 并不重要。有什么想法吗?实际上我有点惊讶我什至能够在 catch 子句中使用 T ,但既然这是可能的,这不应该起作用吗?或者至少给出编译器警告/错误,表明该处理程序永远不会工作?
我的环境是Visual Studio 2008,3.5是目标框架。
更新:我现在直接从命令提示符尝试它,然后打印出“捕获传递异常类型”。所以看起来这仅限于在 Visual Studio 中运行。也许是 Visual Studio 托管过程的一个特点?
这里的行为很奇怪...
VS2k8 控制台应用程序。下列:
try
{
throw new T();
}
catch (T tex)
{
Console.WriteLine("Caught passed in exception type");
}
catch (Exception ex)
{
Console.WriteLine("Caught general exception");
}
结果是“捕获一般异常”.
但是,从 catch 语句中删除(无用的)变量:
try
{
throw new T();
}
catch (T)
{
Console.WriteLine("Caught passed in exception type");
}
catch (Exception)
{
Console.WriteLine("Caught general exception");
}
结果是“捕获异常类型传递”!!!
Update:
呵呵...这是一个错误:
来源?这里。为什么安装 Visual Studio 2008 后,catch(TException) 处理块行为在调试器下有所不同? https://stackoverflow.com/questions/700935/why-does-catchtexception-handling-block-behaviour-differ-under-the-debugger-aft
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)