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

后端 未结 3 1446
夕颜
夕颜 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:11

    It works without Debug

    http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0b0e5bc9-fab2-45b1-863b-40abae370475

    Ugly workaround (you may add #if DEBUG) :

      try
      {
        throw new T();
      }
      catch (Exception dbgEx)
      {
        T ex = dbgEx as T;
        if (ex != null)
        {
          Console.WriteLine(ex.Message);
        }
      }
    

提交回复
热议问题