gpt4 book ai didi

c# - 为什么我不能在 C# 中捕获通用异常?

转载 作者:IT王子 更新时间:2023-10-29 03:57:43 24 4
gpt4 key购买 nike

我正在对可能会根据输入抛出许多异常的代码进行一些单元测试。所以我尝试了类似下面的代码:(针对示例进行了简化)

    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();
}

但是这总是会打印出“Caught general exception”,catch(T tex) 处理程序永远不会工作。我抛出 T() 还是显式抛出 ArgumentException() 并不重要。任何想法为什么会这样?实际上,我什至能够在 catch 子句中使用 T,这让我感到有些惊讶,但既然这是可能的,难道这不可行吗?或者至少给出一个编译器警告/错误,说明此处理程序将永远无法工作?

我的环境是Visual Studio 2008,目标框架是3.5。

更新:我现在直接从命令提示符尝试了它,然后它打印出“Caught passed in exception type”。所以看起来这仅限于从 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");
}

导致“捕获到异常类型”!!!


更新:

呵呵...这是一个错误:https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0

来源?这里。 Why does catch(TException) handling block behaviour differ under the debugger after installing Visual Studio 2008?

关于c# - 为什么我不能在 C# 中捕获通用异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1577760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com