title: Exception handling, WinRT C++ concurrency async tasks
body: <p>I have to implement an async HTTP GET in C++ and we have to be able to submit the app to the Windows 8 Store.</p>
  
  <p>My problem is the following:</p>
  
  <p>I've found a suitable Sample code which implements an HttpRequest class <a href="http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664" rel="nofollow">http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664</a></p>
  
  <p>This example works if the URI is correct but throws an exception if the URI points to an invalid / non existing place (like: www.google22.com). This would be fine if I could catch the exception but I cannot figure it out how or where should I catch it.</p>
  
  <p>Now some code.
  This is the call to the async, concurrency::task based method which throws the exception:</p>
  
  <pre><code>try {
  ...
  Web::HttpRequest httpRequest;
      httpRequest.GetAsync(uri, cancellationTokenSource.get_token())
          .then( []  (concurrency::task&lt;std::wstring&gt; response)
      {
          try {
              response.get();
          }
          catch( ... ) {
              int i = 1;
          }
          return response;
      })
  ...
  } catch ( ... ) {
  ...
  }
  </code></pre>
  
  <p>And this is the relevant segment of the GetAsync method (the end of the method):</p>
  
  <pre><code>// Return a task that completes when the HTTP operation completes. 
  // We pass the callback to the continuation because the lifetime of the 
  // callback must exceed the operation to ensure that cancellation 
  // works correctly.
  return completionTask.then([this, stringCallback](tuple&lt;HRESULT, wstring&gt; resultTuple)
  {
      // If the GET operation failed, throw an Exception.
      CheckHResult(std::get&lt;0&gt;(resultTuple));
  
      statusCode = stringCallback-&gt;GetStatusCode();
      reasonPhrase = stringCallback-&gt;GetReasonPhrase();
  
      return std::get&lt;1&gt;(resultTuple);
  });
  </code></pre>
  
  <p>The CheckHResult line throws the exception, it's code:</p>
  
  <pre><code>inline void CheckHResult(HRESULT hResult)
  {
  if (hResult == E_ABORT)
  {
      concurrency::cancel_current_task();
  }
  else if (FAILED(hResult))
  {
      throw Platform::Exception::CreateException(hResult);
  }
  }
  </code></pre>
  
  <p>I have a try-catch around the GetAsync call and I also have a try-catch in the .then continuation lambda.</p>
  
  <p>In the relevant Microsoft documentation ( <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/apps/hh780559.aspx</a> ) it states that exceptions thrown by a task should be catchable in the next task in the chain but somehow it doesn't work in my case. Additionally not even the try-catch around the whole call catches the exception, it just slips through everything...</p>
  
  <p>Anyone had this problem? I think I've tried everything stated in the official documentations but it still lets the exception go berserk and crash the app. What do I miss?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I've modified the code to do nothing else but exception handling and it still doesn't catch the exception thrown by the task in .GetAsync</p>
  
  <p>Cleaned-up code:</p>
  
  <pre><code>try
  {
    Windows::Foundation::Uri^ uri;
    uri = ref new Windows::Foundation::Uri( uri_string_to_fetch );
  
    concurrency::cancellation_token_source cancellationTokenSource = concurrency::cancellation_token_source();
  
    Web::HttpRequest httpRequest;
    OutputDebugString( L"Start to fetch the uri...\n" );
    httpRequest.GetAsync(uri, cancellationTokenSource.get_token())
      .then([](concurrency::task&lt;std::wstring&gt; response)
    {
      try {
        response.get();
      }
      catch( ... ) {
        OutputDebugString(L"unknown Exception");
      }
    })
    .then([](concurrency::task&lt;void&gt; t)
    {
      try {
        t.get();
        // .get() didn't throw, so we succeeded.
      }
      catch (Platform::Exception^ e) {
        // handle error
        OutputDebugString(L"Platform::Exception");
      }
      catch (...) {
        OutputDebugString(L"unknown Exception");
      }
    });
  } 
  catch (Platform::Exception^ ex) {
    OutputDebugString(L"Platform::Exception");
    errorCallback(-1);
  } 
  catch ( ... ) {
    OutputDebugString(L"unknown Exception");
    errorCallback(-2);
  }
  </code></pre>
  
  <p>This still gives me a crash with the exception message: <em>First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x077EEC28. HRESULT:0x800C0005</em></p>
  
  <p>Additionally when I put some breakpoints in the code it shows that the exception slips through everything before the first .then would be called. I've put breakpoints in these locations (in the simplified / cleaned up code):</p>
  
  <ul>
  <li>before the GetAsync call</li>
  <li>into the GetAsync, to the <strong>CheckHResult(std::get&lt;0>(resultTuple));</strong> line which throws the exception</li>
  <li>into every try and catch case / block</li>
  </ul>
  
  <p>Order of execution, tested with breakpoints:</p>
  
  <ol>
  <li>before the GetAsync call [OK]</li>
  <li>in the GetAsync, the line which will throw the exception [OK]</li>
  <li><strong>now the app crashes, slips through every try-catch</strong>, continue</li>
  <li>now the line in the first <em>.then</em> gets called, in it's try block</li>
  <li>another app level exceptions not catched by any catch block</li>
  <li>now the first <em>.then</em>'s catch block</li>
  <li>second .then method's <em>try</em> block</li>
  <li>and nothing more, the second <em>.then</em>'s catch doesn't even catch any exception</li>
  </ol>
  
  <p>And the printed debug logs, in order:
   - Start to fetch the uri...
   - First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x082FEEF0. HRESULT:0x800C0005
   - First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000.
   - First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x082FE670. HRESULT:0x800C0005
   - First-chance exception at 0x75644B32 in App1.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x082FDD88. HRESULT:0x800C0005
   - unknown Exception</p>
  
  <p>What is happening??</p>