title: Why AccessViolationException cannot be caught by .NET4.0
body: <p>It is really interesting that the following C# code will crash on .NET4.0 but work fine on .NET2.0.</p>
  
  <p><strong>C# code</strong></p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          try
          {
              ExceptionTest();
              Console.WriteLine("Done!");
          }
          catch (Exception e)
          {
              Console.WriteLine("Error !!!");
              Console.WriteLine(e.Message);
          }
      }
  
      [DllImport("badapp")]
      private static extern int ExceptionTest();
  }
  </code></pre>
  
  <p><strong>C++ code</strong></p>
  
  <pre><code>extern "C" __declspec(dllexport) int ExceptionTest()
  {
      IUnknown* pUnk = NULL;
      pUnk-&gt;AddRef();
      return 0;
  }
  </code></pre>
  
  <p>If compiling the above C# code against .NET2.0, everything works fine. Only compiling it against .NET4.0 will make it crash at runtime.</p>
  
  <p>I'm suspecting that system exception catch mechanism has been changed since .NET4.0. Any ideas?</p>