为什么我不能在 C# 中捕获通用异常? [英] Why can't I catch a generic exception in C#?

查看:38
本文介绍了为什么我不能在 C# 中捕获通用异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是这总是会打印出Caught general exception",catch(T tex) 处理程序永远不会工作.我是抛出 T() 还是显式抛出 ArgumentException() 都没有关系.任何想法这是为什么?实际上,我什至能够在 catch 子句中使用 T 令我感到有些惊讶,但是既然这是可能的,那么这不应该起作用吗?或者至少给出一个编译器警告/错误,说明这个处理程序永远不会工作?

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?

推荐答案

这里的奇怪行为...

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

导致捕获传入异常类型"!!!

更新:

嘿嘿...这是一个错误: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

来源?这里.为什么 catch(TException) 处理块行为不同安装 Visual Studio 2008 后在调试器下?

这篇关于为什么我不能在 C# 中捕获通用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆