Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?


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

It would seem that the most specific type of the exception, when given the choice between T and Exception, is exception, and so that handler is invoked.

I just tried this (you can't do it in C# or VB, but I edited the IL), and changed the second catch clause to catch Object Ex rather than Exception Ex, and in that case, the first handler got hit.

Edit

As others have pointed out, it's more to do with running it in the debugger than the specific type