相关疑难解决方法(0)

为什么我不能在C#中捕获一般的异常?

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

    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();
    }
Run Code Online (Sandbox Code Playgroud)

但是这将始终打印出"抓住一般异常",catch(T tex)处理程序永远不会工作.无论我抛出T()还是显式抛出ArgumentException()都没关系.任何想法为什么会这样?实际上我有点惊讶我甚至能够在catch子句中使用T,但是因为那可能不应该这样做吗?或者至少给出一个编译器警告/错误,说明这个处理程序永远不会工作?

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

更新:我现在直接从命令提示符尝试它,然后打印出"Caught传递异常类型".因此看起来这仅限于在Visual Studio中运行.也许Visual Studio托管过程的特殊性?

.net c# generics exception-handling

40
推荐指数
2
解决办法
1万
查看次数

为什么安装Visual Studio 2008后,调试器下的catch(TException)处理块行为会有所不同?

考虑下面的控制台应用程序,其特色是具有捕获类型异常的通用catch处理程序的方法TException.

当使用"调试"配置构建此控制台应用程序并在Visual Studio调试器下执行时(即通过*.vshost.exe),这在Visual Studio 2005和Visual Studio 2008中都会失败.

我相信这个问题只是在我安装Visual Stuido 2008之后才出现的.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(Environment.Version);
        CatchAnException<TestException>();

        Console.ReadKey();
    }

    private static void CatchAnException<TException>()
        where TException : Exception
    {
        Console.WriteLine("Trying to catch a <{0}>...", typeof(TException).Name);
        try
        {
            throw new TestException();
        }
        catch (TException ex)
        {
            Console.WriteLine("*** PASS! ***");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught <{0}> in 'catch (Exception ex)' handler.", ex.GetType().Name);
            Console.WriteLine("*** FAIL! ***");
        }
        Console.WriteLine();
    }
}

internal class TestException : Exception
{
} …
Run Code Online (Sandbox Code Playgroud)

.net c# visual-studio-2008 visual-studio

9
推荐指数
1
解决办法
963
查看次数