0

So I have VS 2017, created New MFC Application, compiled Release x86 build with /clr, Multibyte character set, Optimized favor speed (/O2).

When ::Run function contains __try __except exception handler, the function will not be called in optimized release build, or throws error "Common Language Runtime detected an invalid program.".

When using try-catch or if C/C++ Optimization Disabled (/Od), it works as expected.

    int CMFCTryExceptTestApp::Run()
    {
      ::AfxMessageBox("CMFCTryExceptTestApp::Run");
      for (;;)
      {
        __try
        {
          int ret = CWinAppEx::Run();
          return ret;
        }
        __except (EXCEPTION_EXECUTE_HANDLER)
        {
          ASSERT(FALSE);
        }
      }
    }

This works always:

    int CMFCTryExceptTestApp::Run()
    {
      ::AfxMessageBox("CMFCTryExceptTestApp::Run");
      for (;;)
      {
        try
        {
          int ret = CWinAppEx::Run();
          return ret;
        }
        catch(...)
        {
          ASSERT(FALSE);
        }
      }
    }

I have been also using __try __except elsewhere in the program and it works there.

owluCoder
  • 1
  • 1
  • Found [SO: C++, __try and try/catch/finally](https://stackoverflow.com/questions/7049502/c-try-and-try-catch-finally) which might be related. – Scheff's Cat Oct 05 '18 at 08:00
  • 1
    From the [/clr compiler option](https://learn.microsoft.com/en-us/cpp/build/reference/clr-common-language-runtime-compilation) documentation: *"`/clr` implies `/EHa`, and no other `/EH` options are supported for `/clr`. For more information, see [/EH (Exception Handling Model)](https://learn.microsoft.com/en-us/cpp/build/reference/eh-exception-handling-model)."* – IInspectable Oct 05 '18 at 08:01
  • Are you sure you need `/clr` ? – Jabberwocky Oct 05 '18 at 09:35
  • I made another Run2 function that has __try __except handler there and it seems to work. I really need also C structured error handling because app loads native dlls where may occur c exceptions. – owluCoder Oct 15 '18 at 12:01

0 Answers0