Strange CLR behavior

Here’s a little CLR brain teaser for you:

A method is throwing a NullReferenceException. The stack trace indicates it is originating on a line that has only a closing curly brace on it (i.e. }). How could this be explained?

Note that:

  1. The code is not optimized.
  2. The PDB file is the correct version.
  3. The method has no using statements.
  4. There is no code generation or reflection happening.

Stumped? Okay, here’s a simple case to reproduce it.

void Test()
{
    try
    {
        (null as string).ToLower();
    }
    catch
    {
        throw;
    }
}

If you said this code reports a NullReferenceException on line 5, you’d be wrong. The CLR reports it coming from line 11. Weird, huh? It seems to be something about rethrowing unwrapped NullReferenceExceptions, either as throw or throw e. If I throw new Exception("...", e) it works as expected.

Anyone care to hazard an explanation for this behaviour?

A reference test case is available here, with observed output here. (Compiling under Any CPU, .NET 4 in Debug configuration in VS2010 SP1.)

One thought on “Strange CLR behavior

  1. Not an explanation, but catch{} is a special case meant for catching non-cli compliant exceptions.

    so you can write (despite what resharper says)
    try
    {
    }
    catch(Exception){}
    catch{}

Comments are closed.