{"id":107867,"date":"2023-02-23T07:00:00","date_gmt":"2023-02-23T15:00:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/oldnewthing\/?p=107867"},"modified":"2024-11-06T13:26:29","modified_gmt":"2024-11-06T21:26:29","slug":"20230223-00","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20230223-00\/?p=107867","title":{"rendered":"Why am I getting an unhandled exception from my C++ function that catches all exceptions?"},"content":{"rendered":"<p>A customer had what they thought was a problem with C++\/WinRT coroutines. &#8220;We are catching and handling all exceptions, but sometimes our program still crashes with an unhandled exception.&#8221;<\/p>\n<pre>winrt::fire_and_forget MyClass::DoSomethingAsync()\r\n{\r\n    auto lifetime = get_strong();\r\n    try {\r\n        auto name = co_await m_user.GetNameAsync();\r\n        m_label.Text(name);\r\n    } catch (...) {\r\n        m_label.Text(L\"unknown\");\r\n    }\r\n}\r\n<\/pre>\n<p>The C++\/WinRT knowledge you need to know here is that a coroutine that returns <code>fire_<wbr \/>and_<wbr \/>forget<\/code> terminates the application if an unhandled exception is encountered.<\/p>\n<p>And you can see the unhandled exception in the stack trace:<\/p>\n<pre>KERNELBASE!RaiseFailFastException+0x15c\r\ncombase!RoFailFastWithErrorContextInternal2+0x43a\r\ncontoso!winrt::terminate+0x28\r\ncontoso!std::experimental::coroutine_traits&lt;winrt::fire_and_forget&gt;::promise_type::unhandled_exception+0x9\r\ncontoso!`MyClass::DoSomethingAsync$_ResumeCoro$1'::`1'::catch$2+0x1f\r\nVCRUNTIME140_1+0x1080\r\nVCRUNTIME140_1!_NLG_Return2+0x1555\r\nntdll!RcFrameConsolidation+0x6\r\ncontoso!MyClass::DoSomethingAsync$_ResumeCoro$1+0xa9\r\ncontoso!std::experimental::coroutine_handle&lt;void&gt;::resume+0x5\r\ncontoso!std::experimental::coroutine_handle&lt;void&gt;::operator()+0x5\r\ncontoso!winrt::impl::resume_apartment_callback+0x9\r\n...\r\n<\/pre>\n<p>But we did a <code>catch (...)<\/code>, which catches all exceptions. How did we get an unhandled exception?<\/p>\n<p>The <code>catch (...)<\/code> catches all exceptions thrown in the preceding <code>try<\/code> block. But that&#8217;s not where the unhandled exception is coming from.<\/p>\n<p>The coroutine was just a red herring. Let&#8217;s take coroutines out of the picture and make this a non-coroutine function.<\/p>\n<pre>void MyClass::DoSomething()\r\n{\r\n    try {\r\n        auto name = m_user.GetName();\r\n        m_label.Text(name);\r\n    } catch (...) {\r\n        m_label.Text(L\"unknown\");\r\n    }\r\n}\r\n<\/pre>\n<p>If an exception occurs in the <code>try<\/code> block, it is caught and handled by the <code>catch (...)<\/code> block. But if an exception occurs at the <code>m_label.Text(L\"unknown\")<\/code>, <a title=\"What happens if my C++ exception handler itself raises an exception?\" href=\"https:\/\/devblogs.microsoft.com\/oldnewthing\/20221021-00\/?p=107307\"> there&#8217;s nobody around to catch the <i>second<\/i> exception<\/a>.<\/p>\n<p>You thought you caught the exception, but instead you merely caught <i>an<\/i> exception. If you don&#8217;t want any exceptions to escape your function, you have to play Pok\u00e9mon and <a href=\"https:\/\/www.youtube.com\/watch?v=MpaHR-V_R-o\"> catch them all<\/a>.<\/p>\n<pre>winrt::fire_and_forget MyClass::DoSomethingAsync()\r\n{\r\n    auto lifetime = get_strong();\r\n    try {\r\n        auto name = co_await m_user.GetNameAsync();\r\n        m_label.Text(name);\r\n    } catch (...) {\r\n        <span style=\"border: solid 1px currentcolor;\">try {<\/span>\r\n            m_label.Text(L\"unknown\");\r\n        <span style=\"border: solid 1px currentcolor; border-bottom: none;\">} catch (...) {            <\/span>\r\n        <span style=\"border: 1px currentcolor; border-style: none solid;\">    LOG_CAUGHT_EXCEPTION();<\/span>\r\n        <span style=\"border: solid 1px currentcolor; border-top: none;\">}                          <\/span>\r\n    }\r\n}\r\n<\/pre>\n<p>I&#8217;m assuming that if you can&#8217;t even set the label to <code>L\"unknown\"<\/code> you just want to log the error and proceed anyway. For demonstration purposes, I&#8217;m using the <a href=\"https:\/\/github.com\/microsoft\/wil\/wiki\/Error-handling-helpers\"> WIL error handling helpers<\/a>.<\/p>\n<p>The nesting here is getting rather annoying, but you can make things a little less awkward by using a function try block.<\/p>\n<pre>winrt::fire_and_forget MyClass::DoSomethingAsync() <span style=\"border: solid 1px currentcolor;\">try<\/span>\r\n{\r\n    auto lifetime = get_strong();\r\n    try {\r\n        auto name = co_await m_user.GetNameAsync();\r\n        m_label.Text(name);\r\n    } catch (...) {\r\n        m_label.Text(L\"unknown\");\r\n    }\r\n<span style=\"border-bottom: solid 1px currentcolor;\">} <\/span><span style=\"border: solid 1px currentcolor; border-bottom: none;\">catch (...) {                                     <\/span>\r\n<span style=\"border: 1px currentcolor; border-style: none solid;\">    \/\/ The function is best-effort. Ignore failures.<\/span>\r\n<span style=\"border: solid 1px currentcolor; border-top: none;\">}                                                   <\/span>\r\n<\/pre>\n<p>The function try lets you specify catch blocks that apply to the entire function body.<\/p>\n<p>Next time, we&#8217;ll look at some of the subtle exceptions that can come out of C++\/WinRT and XAML.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Yes, you caught an exception. But that&#8217;s not the one that went unhandled.<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-107867","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>Yes, you caught an exception. But that&#8217;s not the one that went unhandled.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/107867","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=107867"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/107867\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=107867"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=107867"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=107867"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}