Why can't I catch a generic exception in C#?

后端 未结 3 1450
夕颜
夕颜 2020-12-01 01:13

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)

3条回答
  •  半阙折子戏
    2020-12-01 02:01

    Bizarre behavior here...

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

    results in "Caught general exception".

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

    results in "Caught passed in exception type"!!!


    Update:

    Heheh... Its a bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362422&wa=wsignin1.0

    Source? Here. Why does catch(TException) handling block behaviour differ under the debugger after installing Visual Studio 2008?

提交回复
热议问题