title: Access Violation issue with unhandled managed Exceptions in managed C++ .NET application
body: <p>This is actually a solved problem, but it's so esoteric I thought I'd share it for other users.</p>
  
  <p>Also perhaps others might suggest reasons?</p>
  
  <p>Anyway, I'm working on a "mixed mode" .NET application written in managed C++, but with heavy links into existing native libraries.</p>
  
  <p>The problem was, unhandled managed exceptions ended up as Win32 Access Violations. What I mean by this is that instead of showing the nice .NET dialog one gets with an unhandled managed exception, instead I would get the older style "Unhandled win32 exception occurred in..." message.</p>
  
  <p>Here's the interesting thing: if I start the app in the debugger, then the thrown managed exception gets correctly picked up. i.e., the debugger shows me the line. </p>
  
  <p>However, when executing normally, it would turn into this Access Violation. Attaching the debugger at that point would produce little useful information (it wouldn't even show a sensible stack trace).</p>
  
  <p>So, to me it suggests that something is happening in native code just before the unhandled managed exception reaches the exception handler.</p>
  
  <p>So anyway, I managed to solve the issue by comparing my project to a clean new C++ managed project generated by Visual Studio 2008.</p>
  
  <p>The fix was to do the following:</p>
  
  <ol>
  <li><p>Change the /SUBSYSTEM flag (Project properties->Linker->System->SubSystem) <strong>from</strong> /SUBSYSTEM:WINDOWS <strong>to</strong> "Not Set"</p></li>
  <li><p>Switched from using old style WinMain() to using the new style main().</p></li>
  </ol>
  
  <p>i.e. it used to be </p>
  
  <pre><code>  int APIENTRY _tWinMain(HINSTANCE hInstance,
                         HINSTANCE hPrevInstance,
                         LPTSTR    lpCmdLine,
                         int       nCmdShow)
  </code></pre>
  
  <p>And it is now</p>
  
  <pre><code>int main(array&lt;System::String ^&gt; ^args)
  </code></pre>
  
  <p>[Why am I using this weird _tWinMain? This was what got generated by the Visual Studio .NET IDE many years ago when you create a sample mixed mode Windows app. It's always worked fine (until now) so I never bothered changing it. _tWinMain is just a macro to WinMain]</p>
  
  <p>I made this change and the problem disappears. Unhandled .NET exceptions now get properly trapped so I can now actually debug them.</p>
  
  <p>I also made the inverse change to the clean sample C++ app and proved that it was the cause.</p>
  
  <p>So, really my questions is, what the heck is going on?</p>
  
  <p>Was it just that I was using the old style WinMain instead of the new <code>main(array &lt;String^&gt;^)</code>?</p>
  
  <p>Should I maybe report this to Microsoft (will anyone care ;-) )?</p>