    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: C++11 (and beyond) Exception Support</title>
        <link>https://members.accu.org/index.php/articles/2422</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #141 - October 2017</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c378/">o141</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-378/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+378/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;C++11 (and beyond) Exception Support</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 02 October 2017 18:57:54 +01:00 or Mon, 02 October 2017 18:57:54 +01:00</p>
<p><strong>Summary:</strong>&nbsp;C++11 introduced many new exception related features. Ralph McArdell gives a comprehensive overview.</p>
<p><strong>Body:</strong>&nbsp;<p>C++11 added a raft of new features to the C++ standard library and errors and exceptions were not left out.</p>

<p>In this article, we will start with a quick overview of the new exception types and exception related features. While the nitty gritty details are not covered in great depth, in most cases a simple usage example will be provided. The information was pulled together from various sources â€“ [<a href="#[cppreference]">cppreference</a>], [<a href="#[Josuttis12]">Josuttis12</a>], [<a href="#[N3337]">N3337</a>] â€“ and these, along with others, can be used to look up the in depth, detailed, specifics.</p>
<p>Following the lightning tour of C++11 exception support, we will take a look at some further usage examples.</p>

<h2>Example code</h2>

<p>The example code is available with a <code>Makefile</code> for building with GNU g++ 5.4.0 and MSVC++17 project files from: <a href="https://github.com/ralph-mcardell/article-cxx11-exception-support-examples">https://github.com/ralph-mcardell/article-cxx11-exception-support-examples</a></p>

<p>It may be useful to at least browse the source as the full example code is not always shown in the article.</p>

<p>For g++ each was built using the options:</p>

<pre class="programlisting">
  -Wall -Wextra -pedantic -std=c++11 -pthread</pre>
  
<p>For MSVC++17, a Win32 console application solution was created and each example source file added as a project using the default options, or with no pre-compiled header option selected if a project ended up with it turned on.</p>

<h2>New standard library exception types</h2>

<p>So letâ€™s start with a brief look at the new exception types. They are:</p>

<ul>
	<li><code>std::bad_weak_ptr</code> (include <code>&lt;memory&gt;</code>)</li>
	<li><code>std::bad_function_call</code> (include <code>&lt;functional&gt;</code>)</li>
	<li><code>std::bad_array_new_length</code> (include <code>&lt;new&gt;</code>)</li>
	<li><code>std::future_error</code> (include <code>&lt;future&gt;</code>)</li>
	<li><code>std::system_error</code> (include <code>&lt;system_error&gt;</code>)</li>
	<li><code>std::nested_exception</code> (include <code>&lt;exception&gt;</code>)</li>
</ul>

<p>Additionally, starting with C++11, <code>std::ios_base::failure</code> is derived from <code>std::system_error</code>.</p>

<p><code>std::bad_weak_ptr</code> and <code>std::bad_function_call</code> are derived from <code>std::exception</code>.</p>

<p><code>std::bad_weak_ptr</code> is thrown by the <code>std::shared_ptr</code> constructor that takes a <code>std::weak_ptr</code> as an argument if the <code>std::weak_ptr::expired</code> operation returns true (see Listing 1), which should produce output similar to:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
std::weak_ptr&lt;int&gt; int_wptr;
assert( int_wptr.expired() );
try{
  std::shared_ptr&lt;int&gt; int_sptr{ int_wptr };
}
catch ( std::bad_weak_ptr &amp; e ){
  std::cerr 
  &lt;&lt; &quot;Expired or default initialised weak_ptr: &quot;
  &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<pre class="programlisting">
  Expired or default initialised weak_ptr:  bad_weak_ptr</pre>
  
<p>If a <code>std::function </code>object has no target, <code>std::bad_function_call</code> is thrown by <code>std::function::operator()</code> (see Listing 2)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
std::function&lt;void()&gt; fn_wrapper;
assert( static_cast&lt;bool&gt;(fn_wrapper)==false );
try{
  fn_wrapper();
}
catch ( std::bad_function_call &amp; e ){
  std::cerr &lt;&lt; &quot;Function wrapper is empty: &quot; 
  &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>with expected output:</p>

&lt;IMAGE xml:link=&quot;simple&quot; href=&quot;McArdell-3.gif&quot; show=&quot;embed&quot; actuate=&quot;auto&quot;/&gt;

<pre class="programlisting">
 <em>(g++):</em>	Function wrapper is empty:
	bad_function_call
 <em>(msvc++)</em>:	Function wrapper is empty:
	bad function call</pre>
	
<p><code>std::bad_array_new_length</code> is derived from <code>std::bad_alloc</code>, which means it will be caught by existing catch clauses that handle <code>std::bad_alloc</code> exceptions. It is thrown if an array size passed to new is invalid by being negative, exceeding an implementation defined size limit, or is less than the number of provided initialiser values (MSVC++17 does not seem to handle this case). It should be noted that this only applies to the first array dimension as this is the only one that can be dynamic thus any other dimension size values can be checked at compile time. In fact MSVC++17 is able to check the validity of simple literal constant size values for the first dimension as well during compilation, hence the use of the <code>len</code> variable with an illegal array size value in the example in Listing 3.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
int len=-1; // negative length value
try{
  int * int_array = new int[len];
  delete [] int_array;
}
catch ( std::bad_array_new_length &amp; e ){
  std::cerr &lt;&lt; &quot;Bad array length: &quot; 
            &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>When run, we should see output like so:</p>

<pre class="programlisting">
 <em>(g++):</em>	Bad array length:
	std::bad_array_new_length
 <em>(msvc++):	</em>Bad array length: 
	bad array new length</pre>
	
<p><code>std::future_error</code> is derived from <code>std::logic_error</code> and is used to report errors in program logic when using futures and promises, for example trying to obtain a future object from a promise object more than once (see Listing 4), which should display:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
std::promise&lt;int&gt; int_vow;
auto int_future = int_vow.get_future();
try{
  int_future = int_vow.get_future();
}
catch ( std::future_error &amp; e ){
  std::cerr &lt;&lt; &quot;Error from promise/future: &quot; 
            &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<pre class="programlisting">
    <em>(g++):</em>	Error from promise/future:
	std::future_error: Future already
	retrieved
 <em>(msvc++):	</em>Error from promise/future: 
	future already retrieved</pre>
	
<p><code>std::system_error</code> is derived from <code>std::runtime_error</code> and is used to report operating system errors, either directly by our code or raised by other standard library components, as in the example in Listing 5, which on running should produce output along the lines of:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
try{
  std::thread().detach(); // Oops, no thread to
}                         // detach
catch ( std::system_error &amp; e ){
  std::cerr &lt;&lt; &quot;System error from thread detach: &quot; 
  &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<pre class="programlisting">
    <em>(g++):</em>	System error from thread detach: 
	Invalid argument
 <em>(msvc++):</em>	System error from thread detach: 
	invalid argument: invalid argument</pre>
	
<p><code>std::nested_exception</code> is not derived from anything. It is a polymorphic mixin class that allows exceptions to be nested within each other. There is more on nested exceptions below in the â€˜Nesting exceptionsâ€™ section.</p>

<h2>Collecting, passing and re-throwing exceptions</h2>

<p>Since C++11, there has been the capability to obtain and store a pointer to an exception and to re-throw an exception referenced by such a pointer. One of the main motivations for exception pointers was to be able to transport exceptions between threads, as in the case of <code>std::promise</code> and <code>std::future</code> when there is an exceptional result set on the promise.</p>

<p>Exception pointers are represented by the <code>std::exception_ptr</code> standard library type. It is, in fact, a type alias to some unspecified nullable, shared-ownership smart pointer like type that ensures any pointed to exception remains valid while at least one <code>std::exception_ptr </code>object is pointing to it. Instances can be passed around, possibly across thread boundaries. Default constructed instances are null pointers that compare equal to <code>nullptr</code> and test false.</p>

<p><code>std::exception_ptr</code> instances must point to exceptions that have been thrown, caught, and captured with <code>std::current_exception</code>, which returns a <code>std::exception_ptr</code>. Should we happen to have an exception object to hand already, then we can pass it to <code>std::make_exception_ptr</code> and get a <code>std::exception_ptr</code> in return. <code>std::make_exception_ptr</code> behaves as if it throws, catches and captures the passed exception via <code>std::current_exception</code>.</p>

<p>Once we have a <code>std::exception_ptr</code>, it can be passed to <code>std::rethrow_exception()</code> from within a try-block to re-throw the exception it refers to.</p>

<p>The example in Listing 6 shows passing an exception simply via a (shared) global <code>std::exception_ptr</code> object from a task thread to the main thread.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;exception&gt;
#include &lt;thread&gt;
#include &lt;iostream&gt;
#include &lt;cassert&gt;

std::exception_ptr g_stashed_exception_ptr;

void bad_task(){
  try  {
    std::thread().detach(); // Oops !!
  }
  catch ( ... )  {
    g_stashed_exception_ptr =
    std::current_exception();
  }
}

int main(){
  assert( g_stashed_exception_ptr == nullptr );
  assert( !g_stashed_exception_ptr );
  std::thread task( bad_task );
  task.join();
  assert( g_stashed_exception_ptr != nullptr );
  assert( g_stashed_exception_ptr );

  try{
    std::rethrow_exception
      ( g_stashed_exception_ptr );
  }
  catch ( std::exception &amp; e ){
    std::cerr &lt;&lt; &quot;Task failed exceptionally: &quot; 
              &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<p>When built and run it should output:</p>

<pre class="programlisting">
    <em>(g++):</em>	Task failed exceptionally: 
	Invalid argument
 <em>(msvc++):</em>	Task failed exceptionally: 
	invalid argument: invalid argument</pre>
	
<p>Of course, using global variables is questionable at best, so in real code you would probably use other means, such as hiding the whole mechanism by using <code>std::promise</code> and <code>std::future</code>.</p>

<h2>Error categories, codes and conditions</h2>

<p><code>std::system_error</code> and <code>std::future_error</code> allow specifying an error code or error condition during construction. Additionally, <code>std::system_error</code> can also be constructed using an error category value.</p>

<p>In short, error codes are lightweight objects encapsulating possibly implementation-specific error code values, while error conditions are effectively portable error codes. Error codes are represented by <code>std::error_code</code> objects, while error conditions are represented by <code>std::error_condition</code> objects.</p>

<p>Error categories define the specific error-code, error-condition mapping and hold the error description strings for each specific error category. They are represented by the base class <code>std::error_category</code>, from which specific error category types derive. There are several categories defined by the standard library whose error category objects are accessed through the following functions:</p>

<ul>
	<li><code>std::generic_category</code> for POSIX <code>errno</code> error conditions</li>
	<li><code>std::system_category</code> for errors reported by the operating system</li>
	<li><code>std::iostream_category</code> for IOStream error codes reported via <code>std::ios_base::failure</code> (which, if you remember, has been derived from <code>std::system_error</code> since C++11)</li>
	<li><code>std::future_category</code> for future and promise related error codes provided by <code>std::future_error</code></li>
</ul>

<p>Each function returns a <code>const std::error_category&amp;</code> to a static instance of the specific error category type.</p>

<p>The standard library also defines enumeration types providing nice-to-use names for error codes or conditions for the various error categories:</p>

<ul>
	<li><code>std::errc</code> defines portable error condition values corresponding to POSIX error codes</li>
	<li><code>std::io_errc</code> defines error codes reported by IOStreams via <code>std::ios_base::failure</code></li>
	<li><code>std::future_errc</code> defines error codes reported by <code>std::future_error</code></li>
</ul>

<p>Each of the enumeration types have associated <code>std::make_error_code</code> and <code>std::make_error_condition</code> function overloads that convert a passed enumeration value to a <code>std::error_code</code> or <code>std::error_condition</code>. They also have an associated <code>is_error_condition_enum</code> or <code>is_error_code_enum</code> class specialisation to aid in identifying valid enumeration error condition or code types that are eligible for automatic conversion to <code>std::error_condition</code> or <code>std::error_code</code>.</p>

<p>In C++11 and C++14, <code>std::future_error</code> exceptions are constructed from <code>std::error_code</code> values. However, from C++17 they are constructed directly from <code>std::future_errc</code> enumeration values.</p>

<h2>Nesting exceptions</h2>

<p>At the end of the â€˜New standard library exception typesâ€™ section above was a brief description of <code>std::nested_exception</code>, which can be used to allow us to nest one exception within another (and another, and another and so on if we so desire). This section takes a closer look at the support for handling nested exceptions.</p>

<p>While it is possible to use <code>std::nested_exception</code> directly, it is almost always going to be easier to use the C++ standard library provided support.</p>

<p>To create and throw a nested exception, we call <code>std::throw_with_nested</code>, passing it an rvalue reference to the outer exception object. That is, it is easiest to pass a temporary exception object to <code>std::throw_with_nested</code>. <code>std::throw_with_nested</code> will call <code>std::current_exception</code> to obtain the inner nested exception, and hence should be called from within the catch block that handles the inner nested exception.</p>

<p>Should we catch an exception that could be nested then we can re-throw the inner nested exception by passing the exception to <code>std::rethrow_if_nested</code>. This can be called repeatedly, possibly recursively, until the inner most nested exception is thrown where upon the exception is no longer nested and so <code>std::rethrow_if_nested</code> does nothing.</p>

<p>Each nested exception thrown by <code>std::throw_with_nested</code> is publicly derived from both the type of the outer exception passed to <code>std::throw_with_nested</code> and <code>std::nested_exception</code>, and so has an is-a relationship with both the outer exception type and <code>std::nested_exception</code>. Hence nested exceptions can be caught by catch blocks that would catch the outer exception type, which is handy.</p>

<p>The example in Listing 7 demonstrates throwing nested exceptions and recursively logging each to <code>std::cerr</code>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;exception&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;stdexcept&gt;

void log_exception( std::exception const &amp; e, unsigned level = 0u ){
  const std::string indent( 3*level, ' ' );
  const std::string prefix( indent +
    (level?&quot;Nested&quot;:&quot;Outer&quot;) + &quot; exception: &quot; );
  std::cerr &lt;&lt; prefix &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;;
  try{
    std::rethrow_if_nested( e );
  }
  catch ( std::exception const &amp; ne )  {
    log_exception( ne, level + 1 );
  }
  catch( ... ) {}
}

void sub_task4(){
  // do something which fails...
  throw std::overflow_error{
    &quot;sub_task4 failed: calculation overflowed&quot; };
}

void task2(){
  try{ // pretend sub tasks 1, 2 and 3 are
       // performed OK...
    sub_task4();
  }
  catch ( ... ){
    std::throw_with_nested
      ( std::runtime_error{
        &quot;task2 failed performing sub tasks&quot; } );
  }
}

void do_tasks(){
  try{
    // pretend task 1 performed OK...
    task2();
  }
  catch ( ... ){
    std::throw_with_nested
      ( std::runtime_error{
        &quot;Execution failed performing tasks&quot; } );
  }
}

int main(){
  try{
    do_tasks();
  }
  catch ( std::exception const &amp; e ){
    log_exception( e );
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 7</td>
	</tr>
</table>

<p>The idea is that the code is performing some tasks and each task performs sub-tasks. The initial failure is caused by sub-task 4 of task 2 in the <code>sub_task4()</code> function. This is caught and re-thrown nested within a <code>std::runtime_error</code> exception by the <code>task2()</code> function which is then caught and re-thrown nested with another <code>std::runtime_error</code> by the <code>do_tasks</code> function. This composite nested exception is caught and logged in main by calling <code>log_exception</code>, passing it the caught exception reference.</p>

<p><code>log_exception</code> first builds and outputs to <code>std::cerr</code> a log message for the immediate, outer most exception. It then passes the passed in exception reference to <code>std::rethrow_if_nested</code> within a try-block. If this throws, the exception had an inner nested exception which is caught and passed recursively to <code>log_exception</code>. Otherwise the exception was not nested, no inner exception is re-thrown and <code>log_exception</code> just returns.</p>

<p>When built and run the program should produce:</p>

<pre class="programlisting">
 Outer exception: Execution failed performing tasks
   Nested exception: task2 failed performing sub
   tasks
     Nested exception: sub_task4 failed:
     calculation overflowed</pre>

<h2>Detecting uncaught exceptions</h2>

<p>C++98 included support for detecting if a thread has a live exception in flight with the <code>std::uncaught_exception</code> function. A live exception is one that has been thrown but not yet caught (or entered <code>std::terminate</code> or <code>std::unexpected</code>). The <code>std::uncaught_exception</code> function returns true if stack unwinding is in progress in the current thread.</p>

<p>It turns out that <code>std::uncaught_exception</code> is not usable for what would otherwise be one of its main uses: knowing if an objectâ€™s destructor is being called due to stack unwinding, as detailed in Herb Sutterâ€™s N4152 'uncaught exceptions' paper to the ISO C++ committee [<a href="#[N4152]">N4152</a>]. For this scenario knowing the number of currently live exceptions in a thread is required not just knowing if a thread has at least one live exception.</p>

<p>If an objectâ€™s destructor only knows if it is being called during stack unwinding it cannot know if it is because of an exception thrown after the object was constructed, and so needs exceptional clean-up (e.g. a rollback operation), or if it was due to stack unwinding already in progress and it was constructed as part of the clean-up and so probably not in an error situation itself. To fix this an object needs to collect and save the number of uncaught exceptions in flight at its point of construction and during destruction compare this value to the current value and only take exceptional clean-up action if the two are different.</p>

<p>So, from C++17, <code>std::uncaught_exception</code> has been deprecated in favour of <code>std::uncaught_exceptions</code> (note the plural, â€˜sâ€™, at the end of the name) which returns an <code>int</code> value indicating the number of live exceptions in the current thread.</p>

<h2>Some additional usage scenarios</h2>

<p>Now we have had a whizz around the new C++11 exceptions and exception features, letâ€™s look at some other uses.</p>

<h3>Centralising exception handling catch blocks</h3>

<p>Have you ever written code where you wished that common exception handling blocks could be pulled out to a single point? If so then read on.</p>

<p>The idea is to use a catch all <code>catch (â€¦)</code> clause containing a call to <code>std::current_exception</code> to obtain a <code>std::exception_ptr</code> which can then be passed to a common exception processing function where it is re-thrown and the re-thrown exception handled by a common set of catch clauses.</p>

<p>Using the simple C API example shown in Listing 8 allows us to make widgets with an initial value, get and set the attribute value and destroy widgets when done with them. Each API function returns a status code meaning a C++ implementation has to convert any exceptions to <code>status_t</code> return code values. The API could be exercised as shown in Listing 9.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
extern &quot;C&quot;{
  struct widget;
  enum status_t { OK, no_memory, bad_pointer,
    value_out_of_range, unknown_error };
  status_t make_widget
    ( widget ** ppw, unsigned v );
  status_t get_widget_attribute
    ( widget const * pcw, unsigned * pv );
  status_t set_widget_attribute
    ( widget * pw, unsigned v );
  status_t destroy_widget( widget * pw );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 8</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
int main( void ){
  struct widget * pw = NULL;
  assert(make_widget(NULL, 19u) == bad_pointer);
  assert(make_widget(&amp;pw, 9u) ==
    value_out_of_range);
  if (make_widget(&amp;pw, 45u) != OK)
    return EXIT_FAILURE;
  unsigned value = 0u;
  assert(get_widget_attribute(pw, &amp;value) == OK);
  assert(get_widget_attribute(NULL, &amp;value) ==
    bad_pointer);
  assert(value == 45u);
  assert(set_widget_attribute(pw, 67u) == OK);
  assert(set_widget_attribute(NULL, 11u) ==
    bad_pointer);
  assert(set_widget_attribute(pw, 123u) ==
    value_out_of_range);
  get_widget_attribute(pw, &amp;value);
  assert(value == 67u);
  assert(destroy_widget(pw) == OK);
  assert(destroy_widget(NULL) == bad_pointer);
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 9</td>
	</tr>
</table>

<p>We could imagine a simple quick and dirty C++ implementation like Listing 10.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace{
  void check_pointer( void const * p )  {
    if ( p==nullptr )
      throw std::invalid_argument(&quot;bad pointer&quot;);
  }
}

extern &quot;C&quot;{
  struct widget{

  private:
    unsigned attrib = 10u;

  public:
    unsigned get_attrib() const { return attrib; }
    void set_attrib( unsigned v ){
      if ( v &lt; 10 || v &gt;= 100 )
        throw std::range_error
          ( &quot;widget::set_widget_attribute:
            attribute value out of range 
            [10,100)&quot; );
      attrib = v;
    }
  };

  status_t make_widget( widget ** ppw, 
  unsigned v ){
    status_t status{ OK };
    try{
      check_pointer( ppw );
      *ppw = new widget;
      (*ppw)-&gt;set_attrib( v );
    }
    catch ( std::invalid_argument const &amp; ){
      return bad_pointer;
    }
    catch ( std::bad_alloc const &amp; ){
      status = no_memory;
    }
    catch ( std::range_error const &amp; ){
      status = value_out_of_range;
    }
    catch ( ... ){
      status = unknown_error;
    }
    return status;
  }

  status_t get_widget_attribute
  ( widget const * pcw, unsigned * pv ){
    status_t status{ OK };
    try{
      check_pointer( pcw );
      check_pointer( pv );
      *pv = pcw-&gt;get_attrib();
    }
    catch ( std::invalid_argument const &amp; ){
      return bad_pointer;
    }
    catch ( ... ){
      status = unknown_error;
    }
    return status;
  }

  status_t set_widget_attribute( widget * pw,
  unsigned v ){
    status_t status{ OK };
    try{
      check_pointer( pw );
      pw-&gt;set_attrib( v );
    }    catch ( std::invalid_argument const &amp; ){
      return bad_pointer;
    }
    catch ( std::range_error const &amp; ){
      status = value_out_of_range;
    }
    catch ( ... ){
      status = unknown_error;
    }
    return status;
  }

  status_t destroy_widget( widget * pw ){
    status_t status{ OK };
    try{
      check_pointer( pw );
      delete pw;
    }
    catch ( std::invalid_argument const &amp; ){
      return bad_pointer;
    }
    catch ( ... ){
      status = unknown_error;
    }
    return status;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 10</td>
	</tr>
</table>

<p>Not to get hung up on the specifics of the implementation and that I have added a <code>check_pointer</code> function to convert bad null pointer arguments to exceptions just for them to be converted to a status code, we see that the error handling in each API function is larger than the code doing the work, which is not uncommon.</p>

<p>Using <code>std::current_exception</code>, <code>std::exception_ptr</code> and <code>std::rethrow_exception</code> allows us to pull most of the error handling into a single function (Listing 11).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace{
  status_t handle_exception
  ( std::exception_ptr ep ){
    try{
      std::rethrow_exception( ep );
    }
    catch ( std::bad_alloc const &amp; ){
      return no_memory;
    }
    catch ( std::range_error const &amp; ){
      return value_out_of_range;
    }
    catch ( std::invalid_argument const &amp; ){
      // for simplicity we assume all bad 
      // arguments are bad pointers
      return bad_pointer;
    }
    catch ( ... ){
      return unknown_error;
    }
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 11</td>
	</tr>
</table>

<p>Now each functionâ€™s <code>try</code> block only requires a <code>catch (â€¦)</code> clause to capture the exception and pass it to the handling function and, for example, the <code>set_widget_attribute</code> implementation becomes Listing 12.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
  status_t set_widget_attribute( widget * pw,
  unsigned v ){
    status_t status{ OK };
    try{
      check_pointer( pw );
      pw-&gt;set_attrib( v );
    }
    catch ( ... ){
      status = handle_exception
      ( std::current_exception() );
    }
    return status;
  }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 12</td>
	</tr>
</table>

<p>We can see that the implementation is shorter and, more importantly, no longer swamped by fairly mechanical and repetitive error handling code translating exceptions into error codes, all of which is now performed in the common <code>handle_exception</code> function.</p>

<p>We can reduce the code clutter even more, at the risk of potentially greater code generation and call overhead on the good path, by using the execute-around pattern [<a href="#[Vijayakumar16]">Vijayakumar16</a>] (more common in languages like Java and C#) combined with lambda functions. (thanks to Steve Love [<a href="#[Love]">Love</a>] for mentioning execute around to me at the ACCU London August 2017 social evening).</p>

<p>The idea is to move the work-doing part of each function, previously the code in each of the API functionsâ€™ try-block, to its own lambda function and pass an instance of this lambda to a common function that will execute the lambda within a try block which has the common exception catch handlers as in the previous incarnation. As each lambda function in C++ is a separate, unique, type we have to use a function template, parametrised on the (lambda) function type (Listing 13).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
template &lt;class FnT&gt;
status_t try_it( FnT &amp;&amp; fn ){
  try{
    fn();
  }
  catch ( std::bad_alloc const &amp; ){
    return no_memory;
  }
  catch ( std::range_error const &amp; ){
    return value_out_of_range;
  }
  catch (std::invalid_argument const &amp; ){
    // for simplicity we assume all bad 
    // arguments are bad pointers
    return bad_pointer;
  }
  catch ( ... ){
    return unknown_error;
  }
  return OK;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 13</td>
	</tr>
</table>

<p>The form of each API function implementation is now shown by the third incarnation of the <code>set_widget_attribute</code> implementation (Listing 14).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
status_t set_widget_attribute
( widget * pw, unsigned v ){
  return try_it( [pw, v]() -&gt; void{
      check_pointer( pw );
      pw-&gt;set_attrib( v );
    }
  );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 14</td>
	</tr>
</table>

<h2>Using nested exceptions to inject additional context information</h2>

<p>As I hope was apparent from the â€˜Nesting exceptionsâ€™ section above, nested exceptions allow adding additional information to an originally thrown (inner most) exception as it progresses through stack unwinding.</p>

<p>Of course, doing so for every stack frame is possible but very tedious and probably overkill. On the other hand, there are times when having some additional context can really aid tracking down a problem.</p>

<p>One area I have found that additional context is useful is threads. You have an application, maybe a service or daemon, that throws an exception in a worker thread. You have carefully arranged for such exceptions to be captured at the thread function return boundary and set them on a promise so a monitoring thread (maybe the main thread) that holds the associated future can re-throw the exception and take appropriate action which always includes logging the problem.</p>

<p>You notice that an exception occurs in the logs, it is a fairly generic problem â€“ maybe a <code>std::bad_alloc</code> or some such. At this point, you are wondering which thread it was that raised the exception. You go back to your thread wrapping code and beef up the last-level exception handling to wrap any exception in an outer exception that injects the threadâ€™s contextual information and hand a <code>std::exception_ptr</code> to the resultant nested exception to the promise object.</p>

<p>The contextual information could include the thread ID and maybe a task name. If the thread is doing work on behalf of some message or event then such details should probably be added to the outer exceptionâ€™s message as these will indicate what the thread was doing.</p>

<p>Of course, the thread exit/return boundary is not the only place such contextual information can be added. For example in the event case mentioned above it may be that adding the message / event information is better placed in some other function. In this case you may end up with a three-level nest exception set: the original inner most exception, the middle event context providing nested exception and the outer thread context providing nested exception.</p>

<h2>Error codes of your very own</h2>

<p>I saw the details of this usage example explained quite nicely by a blog post of Andrzej Krzemienski [<a href="#[Krzemienski17]">Krzemienski17</a>] that was mentioned on ISO Cpp [<a href="#[ISO]">ISO</a>].</p>

<p>The cases where this is relevant are those where a project has sets of error values, commonly represented as enumeration values. Large projects may have several such enumeration types for different subsystems and the enumeration values they employ may overlap. For example, we might have some error values from a gameâ€™s application engine and its renderer sub-system (Listing 15 and Listing 16).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace the_game{
  enum class appengine_error{
    no_object_index  = 100
  , no_renderer
  , null_draw_action = 200
  , bad_draw_context = 300
  , bad_game_object
  , null_player      = 400
  };
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 15</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace the_game{
  enum class renderer_error{
    game_dimension_too_small = 100
  , game_dimension_bad_range
  , board_too_small          = 200
  , board_bad_range
  , game_dimension_bad
  , board_not_square         = 300
  , board_size_bad
  , bad_region               = 400
  , cell_coordinate_bad      = 500
  , new_state_invalid
  , prev_state_invalid
  };
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 16</td>
	</tr>
</table>

<p><strong>Note: </strong>The error types and values were adapted from panic value types from a simple noughts and crosses (tic tac toe) game I wrote with a friend more than a decade ago with the goal of learning a bit about Symbian mobile OS development.</p>

<p>In such cases we can either deal in the enumeration types directly when such error values are passed around with the effect that the various parts of the project need access to the definitions of each enumeration type they come into contact with. Or we can use a common underlying integer type, such as <code>int</code>, for passing around such error value information and lose the ability to differentiate between errors from different subsystems or domains that share the same value.</p>

<p><strong>Note: </strong>It would be possible to use different underlying types for each of the various error value sets but there are only so many and such an approach seems fragile at best given the ease with which C++ converts/promotes between fundamental types and the need to ensure each enumeration uses a different underlying type.</p>

<p>If only C++ had an error code type as standard that would allow us to both traffic in a single type for error values and allow us to differentiate between different sets of errors that may use the same values. If we could also assign a name for each set and text descriptions for each error value that would be icing on the cake. Oh, wait, it does: <code>std::error_code</code>. We just have to plug our own error value enumeration types into it. The only caveats are that all the underlying values be correctly convertible to <code>int</code> and that our custom error types must reserve an underlying value of 0 to mean OK, no error. Even if our error value types do not provide an OK enumeration value of 0 explicitly so long as a value of 0 is not reserved for an error value then we can always create a zero valued instance of the error enum:</p>

<pre class="programlisting">
  the_game::appengine_error ok_code_zero_value{};</pre>
  
<p>Different error value sets or domains are called error categories by the C++ standard library and to completely define an error code we require an {error value, error category} pair.</p>

<p>To create our own error categories, we define a specialisation of <code>std::error_category</code> for each error value set we have. To keep <code>std::error_code</code> lightweight, it does not store a <code>std::error_category</code> object within each instance. Rather each <code>std::error_category</code> specialisation has a single, static, instance. <code>std::error_code</code> objects contain the error value and a reference (pointer) to the relevant <code>std::error_category</code> specialisation static instance. Because all references to an error category type instance refer to the same, single instance of that type, the objectâ€™s address can be used to uniquely identify and differentiate each specific error category and allows <code>std::error_code</code> objects to be compared.</p>

<p>Each <code>std::error_category</code> specialisation provides overrides of the <code>name</code> and <code>message</code> pure virtual member functions. The <code>name</code> member function returns a C-string representing the name of the category. The <code>message</code> member function returns a <code>std::string</code> describing the passed in category error value (passed as an <code>int</code>). For example, an error category type for the <code>the_game::appengine_error</code> error values might look like Listing 17.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
struct appengine_error_category : std::error_category{
  const char* name() const noexcept override;
  std::string message(int ev) const override;
};

const char* appengine_error_category::name() const noexcept{
  return &quot;app-engine&quot;;
}

std::string appengine_error_category::message
  ( int ev ) const{
  using the_game::appengine_error;

  switch( static_cast&lt;appengine_error&gt;(ev) ){
    case appengine_error::no_object_index:
      return &quot;No object index&quot;;
    case appengine_error::no_renderer:
      return &quot;No renderer currently set&quot;;
    case appengine_error::null_draw_action:
      return &quot;Null draw action pointer&quot;;
    case appengine_error::bad_draw_context:
      return &quot;Draw action context has null
      graphics context or renderer pointer&quot;;
    case appengine_error::bad_game_object:
      return &quot;Draw action context has null game
      object pointer&quot;;
    case appengine_error::null_player:
      return &quot;Current player pointer is null&quot;;
    default:
      return &quot;?? unrecognised error ??&quot;;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 17</td>
	</tr>
</table>

<p>To create <code>std::error_code</code> values from a custom error (enumeration) value in addition to the <code>std::error_category</code> specialisation, we need to provide two other things. First, an overload of <code>std::make_error_code</code> that takes our error value type as a parameter and returns a <code>std::error_code</code> constructed from the passed error value and the static <code>std::error_category</code> specialisation object. This should be in the same namespace as our error value enum type.</p>

<p>In this use case, the <code>std::make_error_code</code> function overload is the only thing that requires access to the custom error category static instance. As such we can define the static object to be local to the <code>std::make_error_code</code> function overload, as in Listing 18.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace the_game{
  std::error_code make_error_code
    (appengine_error e){
    static const appengine_error_category
      theappengine_error_categoryObj;
    return {static_cast&lt;int&gt;(e),
      theappengine_error_categoryObj};
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 18</td>
	</tr>
</table>

<p>As the <code>std::make_error_code</code> function overload definition is the only thing that requires the definition of the <code>std::error_category</code> specialisation it is probably best if they are both placed in the same implementation file. The declaration can be placed in the same header as the custom error value enumeration type definition as it will be used when converting such values to <code>std::error_code</code> instances â€“ the <span class="filename">appengine_error.h</span> header for the <code>appengine_error</code> example case.</p>

<p>Second, we need to provide a full specialisation of the <code>std::is_error_code_enum</code> struct template, specifying our error code type as the template parameter. The easiest implementation is to derive from <code>std::true_type</code> and have an empty definition. This should be in the <code>std</code> namespace, one of the few things application code can add to <code>std</code>. Listing 19 shows the <code>std::is_error_code_enum</code> specialisation for <code>the_game::appengine_error</code>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
namespace std{
  using the_game::appengine_error;
  template &lt;&gt; struct
    is_error_code_enum&lt;appengine_error&gt; 
    : true_type {};
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 19</td>
	</tr>
</table>

<p>It is also probably best placed in the same header as the custom error values enumeration type definition.</p>

<p>Subsystem API (member) functions can then pass around <code>std::error_code</code> instances rather than specific enumeration types or simple integer values that loose the category information. Producers of such error codes need to include both <code>system_error</code> for <code>std::error_code</code> and the header containing the error value enum definition, along with the <code>std::make_error_code</code> overload <em>declaration</em> (only) and the <code>std::is_error_code_enum</code> struct template specialisation definition. So to produce <code>std::error_code</code> objects from <code>the_game::appengine_error</code> values, the previously mentioned <span class="filename">appengine_error.h</span> header would need to be included.</p>

<p>Consumers need only include <code>system_error</code> for <code>std::error_code</code> and will still be able to access the error value, category name and error value description string.</p>

<p>For example some spoof game <code>appengine</code> implementation code for updating the game board might complain if it does not have an associated renderer object to pass on the request to by returning a <code>the_game::appengine_error::no_renderer</code> error converted to a <code>std::error_code</code> (Listing 20).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
std::error_code appengine::update_game_board(){
  // good case demonstrates zero-initialising
  // enum class instance
  return rp_ ? appengine_error{} :
  appengine_error::no_renderer;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 20</td>
	</tr>
</table>

<p>It thus needs to include the <span class="filename">appengine_error.h</span> header and well as <code>system_error</code>. However, the caller of this member function only sees the returned <code>std::error_code</code>, and so only needs to include <code>system_error</code>, as well as any <code>appengine</code> API headers of course. This is demonstrated by the simple spoof usage program in Listing 21, which shows spoof usage for both converted <code>the_game::renderer_error</code> values and the <code>the_game::appengine_error</code> values I have shown examples of. When built and run the output should be:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &quot;custom_error_code_bits/the_game_api.h&quot;
#include &lt;system_error&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;

void log_bad_status_codes( std::error_code ec ){
  if ( ec )
    std::clog &lt;&lt; ec &lt;&lt; &quot; &quot; &lt;&lt; ec.message() 
              &lt;&lt; &quot;\n&quot;;
}

int main(){
  auto &amp; engine{ the_game::get_appengine() };

  // Should fail as setting renderer supporting
  // invalid dimension range
  std::unique_ptr&lt;the_game::renderer&gt; rend{
    new the_game::oops_renderer};
  log_bad_status_codes( engine.take_renderer(
    std::move(rend) ) );

  // Should fail as no renderer successfully set to
  // draw board
  log_bad_status_codes
    ( engine.update_game_board() );

  // OK - nothing to report, this renderer is fine
  // and dandy
  rend.reset( new the_game::fine_renderer );
  log_bad_status_codes( engine.take_renderer
    ( std::move(rend)) );

  // OK - now have renderer to render board updates
  log_bad_status_codes
    ( engine.update_game_board() );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 21</td>
	</tr>
</table>

<pre class="programlisting">
  renderer:101 Reported max. supported game grid
  less than the min.
  app-engine:101 No renderer currently set</pre>
  
<p>Of course this is all about error values, codes and categories, nothing about exceptions (other than returning <code>std::error_code</code> values could allow functions to be marked <code>noexcept</code>). Remember however that we can always construct a <code>std::system_error</code> exception object from a <code>std::error_code</code> object.</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[cppreference]"></a>[cppreference] <a href="http://en.cppreference.com">http://en.cppreference.com</a></p>

<p class="bibliomixed"><a id="[ISO]"></a>[ISO] Cpp: <a href="https://isocpp.org/">https://isocpp.org/</a></p>

<p class="bibliomixed"><a id="[Josuttis12]"></a>[Josuttis12] Josuttis, Nicolai M. (2012) <em>The C++ Standard Library</em>, second edition, Addison Wesley Longman</p>

<p class="bibliomixed"><a id="[Krzemienski17]"></a>[Krzemienski17] Your own error code, Andrzej Krzemienski: <a href="https://akrzemi1.wordpress.com/2017/07/12/your-own-error-code/">https://akrzemi1.wordpress.com/2017/07/12/your-own-error-code/</a></p>

<p class="bibliomixed"><a id="[Love]"></a>[Love] Steve Love: <a href="https://uk.linkedin.com/in/steve-love-1198994">https://uk.linkedin.com/in/steve-love-1198994</a></p>

<p class="bibliomixed"><a id="[N3337]"></a>[N3337] Post C++11 Working Draft, Standard for Programming Language C++</p>

<p class="bibliomixed"><a id="[N4152]"></a>[N4152] Herb Sutter, uncaught_exceptions: <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4152.pdf">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4152.pdf</a></p>

<p class="bibliomixed"><a id="[Vijayakumar16]"></a>[Vijayakumar16] Design Patterns â€“ Execute Around Method Pattern: <a href="http://www.karthikscorner.com/sharepoint/design-patterns-execute-around-method-pattern/">http://www.karthikscorner.com/sharepoint/design-patterns-execute-around-method-pattern/</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
