<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta name="GENERATOR" content="Microsoft FrontPage 5.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Cloning and Throwing Dynamically Typed Exceptions</title>
</head>

<body>

<p>Doc. no.&nbsp;&nbsp; WG21/N2106=06-0176<br>
Date:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
<!--webbot bot="Timestamp" s-type="EDITED" s-format="%Y-%m-%d" startspan -->2006-10-23<!--webbot bot="Timestamp" endspan i-checksum="12042" --><br>
Project:&nbsp;&nbsp;&nbsp;&nbsp; Programming Language C++<br>
Reply to:&nbsp;&nbsp; Beman Dawes &lt;<a href="mailto:bdawes@acm.org">bdawes@acm.org</a>&gt;</p>

<h1>Cloning and Throwing Dynamically Typed Exceptions<br>
<font size="5">(Supporting exception propagation from threads)</font></h1>

<p><a href="#Introduction">Introduction</a><br>
<a href="#One">Part One: Dynamic clone and throw functions (compiler support not 
required)</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Proposed-1">Proposed library changes</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Rationale-1">Rationale for mixin approach</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Standard-1">Impact on the Standard</a><br>
&nbsp;&nbsp;&nbsp; <a href="#code-1">Impact on existing code</a><br>
<a href="#Two">Part Two: Dynamic clone and throw functions (compiler support 
required)</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Proposed-2">Proposed library changes</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Rationale-2">Rationale for library approach</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Standard-2">Impact on the Standard</a><br>
&nbsp;&nbsp;&nbsp; <a href="#code-2">Impact on existing code</a><br>
<a href="#Three">Part Three: Exception propagation from threads</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Three">Motivation</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Discussion">Discussion</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Interaction">Interaction with other proposals</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Proposed-3">Proposed changes</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Q">Q &amp; A</a><br>
&nbsp;&nbsp;&nbsp; <a href="#Issues">Open issues</a><br>
<a href="#Implementation">Implementation experience using the proposed mixin</a><br>
<a href="#Acknowledgements">Acknowledgements</a><br>
<a href="#History">Revision history</a>&nbsp;&nbsp;&nbsp; </p>

<h2><a name="Introduction">Introduction</a></h2>

<p>The underlying problem addressed in this proposal is a need to catch an 
exception by dynamic type (i.e. derived class), save it and later rethrow it, 
knowing only the static type (i.e. base class), and then finally to catch it 
again using the derived type.</p>

<p>Although this behavior might be useful elsewhere, it becomes a pressing need 
if exceptions are to be propagated from a thread-of-execution to its joining 
thread.</p>

<p>Here is a non-threaded example of the problem expressed in psuedo-C++:</p>

<blockquote>
  <pre>class B {
  /* ... */
  virtual ~B();
};

class D : public B {
  /*...*/
};

void f() { throw D(); }

int g()
{
  B * p = 0;

  try { 
    f();
  }

  catch ( const B &amp; ex ) {
    p = dynamic_new B(ex); // effectively: new D(ex)
  }

  // ...

  try {
    if ( p ) dynamic_throw p; // type thrown is D
  }

  catch ( const D &amp; ex ) {
    // we want this catch to be executed
  }
  catch ( const B &amp; ex ) {
    // we don't want this catch to be executed
  }
}</pre>
</blockquote>
<p>An early version of this paper was discussed at the Redmond ad hoc threads 
meeting in August, 2006. Many participants contributed suggestions, and there 
was a strong consensus to go forward with a library based approach to exception 
propagation from threads while pursuing both library and core language 
approaches to cloning and throwing exceptions based on dynamic type, which is 
needed to support implementation of exception propagation.</p>

<ul>
  <li>Part one of this paper proposes a library based solution for cloning and 
  throwing exceptions based on dynamic type that does not require compiler 
  support. It allows exception propagation from threads under the current 
  language rules, but is also useful outside of a threading context.<br>
&nbsp;</li>
  <li>Part two proposes a library based solution for cloning and throwing 
  exceptions based on dynamic type that requires compiler support. It allows 
  exception propagation from threads, but is also useful outside of a threading 
  context.<br>
&nbsp;</li>
  <li>Part three proposes adding exception propagation from 
  threads to the threading library currently under consideration by the Library 
  Working Group. It is applicable regardless of the particulars of the eventual 
  threading library, and regardless of the implementation technique. It will 
  probably be superceded by similar facilities in specific thread library proposals 
  from others, but nevertheless serves as the motivation for parts one and two. </li>
</ul>

<h2>Part <a name="One">One</a>: Dynamic clone and throw functions (compiler 
support not required)</h2>

<h3><a name="Proposed-1">Proposed</a> library changes</h3>

<p>To 18.7.1, Class exception, change::</p>

<blockquote>

<p><code>class exception {</code></p>

</blockquote>

<p>to:</p>

<blockquote>

<p><code>class exception : public virtual cloneable {</code></p>

</blockquote>

<p>and add:</p>

  <blockquote>

  <pre>exception * dynamic_clone() const;</pre>
  <blockquote>
    <p><i>Returns:</i> <code>new cloneable(*this)</code></p>
  </blockquote>
  <pre>void dynamic_throw() const;</pre>
  <blockquote>
    <p><i>Throws: </i><code>*this</code></p>
  </blockquote>

</blockquote>

<p>To a header to be decided, add:</p>
<blockquote>
  <pre>namespace std
{
  class cloneable
  {
  public:
    virtual cloneable *  dynamic_clone() const =0;
    virtual void         dynamic_throw() const =0;
    virtual ~cloneable() {}
  };
}</pre>
  <p><b>Class <code>cloneable</code></b></p>
  <p>Class <code>cloneable</code> provides a mixin base class for objects that 
  need to clone themselves or throw themselves based on dynamic type.</p>
  <p><i>[Examples:</i></p>
  <pre>class my_exception : public std::exception
{
public:
  my_exception *  dynamic_clone() const { return new my_exception(*this); }
  void            dynamic_throw() const { throw *this; }

  // ...
};</pre>
</blockquote>
<blockquote>
  <pre>class non_std_exception : public virtual std::cloneable
{
public:
  non_std_exception *  dynamic_clone() const { return new non_std_exception(*this); }
  void                 dynamic_throw() const { throw *this; }

  // ...
};</pre>
  <p><i>-- end examples]</i></p>
</blockquote>

<h3><a name="Rationale-1">Rationale</a> for mixin approach</h3>

<p>Users will need to write catch clauses for specific exception classes, both 
Standard Library and user-defined. To implement this behavior, it must be 
possible save and re-throw exceptions without knowing anything more than their 
base class. The <code>dynamic_clone</code> and <code>dynamic_throw</code> functions 
make this possible. Using a mixin base class allows degraded functionality even 
when the version of the Standard Library used does not itself use the mixin. It 
also works for user-defined exception types no derived from <code>std::exception</code>.</p>

<h3>Impact on the <a name="Standard-1">Standard</a></h3>

<p>This is a pure library proposal. It can be portably 
implemented with any C++03 compiler. It's impact on the standard is limited to 
the change to <code>std::exception</code>.</p>

<h3>Impact on existing <a name="code-1">code</a></h3>

<p>No practical impact foreseen. It is remotely possible that some existing code 
somehow depends on std::exception having no base class, but that seems pretty 
unlikely.</p>

<h2>Part <a name="Two">Two</a>: Dynamic clone and throw functions (compiler 
support required)</h2>

<p><i>Note well: It is not yet known if it is even feasible for compilers to 
provide the required support, or what the cost would be.</i></p>

<h3><a name="Proposed-2">Proposed</a> library changes</h3>

<p>To a header to be decided, add:</p>
<blockquote>
  <pre>namespace std
{
  template&lt; class T &gt;
  T * dynamic_clone( const T &amp; x );

  template&lt; class T &gt;
  void dynamic_throw( const T &amp; x );
}</pre>
</blockquote>

<p>The functions in this section are described in terms of types <code>T</code> 
and <code>D</code>, and an argument <code>x</code> of type <code>T</code>. <code>
T</code> is the type given by the template parameter. If <code>T</code> has any 
virtual functions, <i>
<code>D</code></i> is the dynamic type (1.3.4, dynamic type) of <code>x</code>. 
Otherwise, <i><code>D</code></i> is the same type as <code>T</code>.</p>

<p><i>[Note:</i> Full implementation of these functions requires compiler 
support. If such support is not available, <i><code>D</code></i> shall be 
treated as being the same type as <code>T</code>.<i>&nbsp; </i>This latitude for 
implementors will be removed in the future. --<i> end note]</i></p>

<p><code>template&lt; class T &gt;<br>
T * dynamic_clone( const T &amp; x );</code></p>

<blockquote>

<p><i>Returns:</i> <code>new <i>D</i>(x)</code></p>

</blockquote>

<p><code>template&lt; class T &gt;<br>
void dynamic_throw( const T &amp; x );</code></p>

<blockquote>

<p><i>Effects:</i> Throws <code>dynamic_cast&lt;const <i>D</i> &amp;&gt;(x)</code>.</p>

</blockquote>

<h3><a name="Rationale-2">Rationale</a> for library approach</h3>

<p>The rationale of a library approach is simply to avoid addition of new 
keywords to the core language. Adding new keywords has a much greater potential 
impact on existing user code than adding new standard library functions.</p>

<h3>Impact on the <a name="Standard-2">Standard</a></h3>

<p>This is a pure library proposal. It has no impact other impact on the 
standard.</p>

<h3>Impact on existing <a name="code-2">code</a></h3>

<p>None.</p>

<h2>Part <a name="Three">Three</a>: Exception propagation from threads</h2>

<h3><a name="Motivation">Motivation</a></h3>

<p>In a thread of execution other than the initial (main) thread, what is useful yet safe behavior  if no matching exception handler is found 
after an exception is thrown?</p>

<p>Users of the Boost threading library, which does not currently do anything 
special with exceptions, have asked time-and-time again that the exception to be 
caught by the thread library mechanism and saved, and then 
re-thrown by the thread object's <code>join()</code> function or equivalent.</p>

<h3><a name="Discussion">Discussion</a></h3>

<p>Within a thread of execution, an exception will presumably cause a search for 
an exception handler as in any C++ program. Absent any thread library support 
for exception propagation, if no 
matching exception handler is found within the thread of execution, then <code>std::terminate()</code> will be 
called (15.3/9).</p>

<p>But just as in single-thread programs, it is highly desirable that 
exceptions propagate from a function to its caller. Because a thread's 
processing function is in a different thread of execution from its joining function 
(i.e. caller) doesn't change that. If exceptions do not propagate out of 
a thread of execution to its joining function, programmers are forced to construct ad hoc 
error recovery techniques of the worst kind, such as catching exceptions 
themselves and converting them to error codes (which are too often ignored by 
the joiner, with disastrous effects).</p>

<h3><a name="Interaction">Interaction</a> with other proposals</h3>

<p>Proposals dealing with a C++ memory model that supports multi-threading will 
presumable change 15.3, Handling an exception, paragraph 9 as indicated:</p>
<blockquote>

<p>If no matching handler is found in <strike><font color="#FF0000">a program</font></strike>
<u><font color="#008080">the current thread of execution</font></u>, the 
function <code>std::terminate()</code> is called; whether or not the stack is 
unwound before this call to std::terminate() is implementation-defined (15.5.1).</p>
</blockquote>

<h3><a name="Proposed-3">Proposed</a> changes</h3>

<p>Add&nbsp; a class <code>thread_exception_error</code> derived from <code>std::_runtime_error</code>, 
details to be supplied.</p>
<p>To the launcher function, add:</p>
<blockquote>
<p><i>Effects:</i> If an exception is thrown by the thread function, and the 
thread has not been detached, the exception is caught and saved (see join and 
destructor). Otherwise, <code>std::terminate()</code> is called.</p>
</blockquote>
<p>To the join function, add:</p>
<blockquote>
  <p><i>Throws:</i> If an exception occurred in the thread function,</p>
  <ul>
    <li>If the exception was 
  of a type derived from <code><a href="#Proposed-2">cloneable</a></code>, 
  a copy of the originally thrown object.</li>
    <li>Otherwise, an object of type <code>std::thread_exception_error</code>.</li>
  </ul>
</blockquote>
  <p>To the thread destructor, add:</p>
<blockquote>
  <p><i>Effects:</i> If the thread object's thread-of-execution ended with an 
  uncaught exception 
  and the join function has not been called, call <code>std::terminate()</code>.</p>
</blockquote>
<h3><a name="Q">Q</a> &amp; A</h3>
<p><b>What happens if an exception is thrown by the joining thread before the 
call to a join which has a pending exception reached?</b> The exception caused 
by the joining thread is propagated as usual. There is no effect on the join's 
pending exception - it is still pending.</p>
<p><b>What happens if several threads have pending exceptions?</b> For each join 
for a thread with a pending exception, the join rethrows when reached (if ever). 
The fact that there are pending exceptions for other threads has no impact.</p>
<p><b>What happens on a join_all if multiple exceptions are pending?</b> This 
could depend on the specification of a join_all, but it is clear that multiple 
pending exceptions should not cause a termination.&nbsp; And that at least one 
exception should propagate out. </p>
<p><b>Should there be a thread launching function for thread that always 
terminates on uncaught exceptions, and another for a thread that always catches 
(and rethrows at join)?</b> Yes. This should flow naturally from a layered 
approach to the thread library's design. </p>
<h3>Open <a name="Issues">Issues</a></h3>
<ul>
  <li>Is a <code>nothrow</code> version of <code>join()</code>, or equivalent to <code>join()</code>, needed?</li>
  <li>Is <code>bool exception_pending() const</code> needed?</li>
  <li>Is getting a pointer to a pending exception needed?</li>
</ul>

<h2><a name="Implementation">Implementation</a> experience using the proposed 
mixin</h2>
<p>Boost threads was hacked to provide the proposed functionality. The following 
<a name="program">program</a> illustrates the results:</p>
<blockquote>
  <pre>#include &lt;boost/thread/thread.hpp&gt;
#include &lt;boost/thread/mutex.hpp&gt;
#include &lt;boost/cloneable.hpp&gt;
#include &lt;stdexcept&gt;
#include &lt;iostream&gt;
boost::mutex cout_mutex; // cout race prevention;

class my_exception
  : public std::runtime_error, public virtual boost::cloneable
{
public:
  my_exception( const std::string &amp; s ) : runtime_error( s ) {}
  ~my_exception()                    {}
  my_exception *  dynamic_clone() const { return new my_exception(*this); }
  void            dynamic_throw() const { throw *this; }
};

class foo
{
  int m_argc;
public:
  foo( int argc ) : m_argc( argc ) {}
  void operator()()
  {
    boost::mutex::scoped_lock lock(cout_mutex);
    std::cout &lt;&lt; &quot;starting thread function&quot; &lt;&lt; std::endl;
    if ( m_argc &gt; 1 ) throw my_exception(&quot;\&quot;what-string\&quot;&quot;);
    std::cout &lt;&lt; &quot;normal return from thread function&quot; &lt;&lt; std::endl;
  }
};

int main( int argc, char * argv[] )
{
  foo child(argc);
  std::cout &lt;&lt; &quot;starting thread&quot; &lt;&lt; std::endl;
  boost::thread t(child);

  {
    boost::mutex::scoped_lock lock(cout_mutex);
    std::cout &lt;&lt; &quot;calling join&quot; &lt;&lt; std::endl;
  }
  try { t.join(); }

  catch ( const my_exception &amp; ex )  // catch #1
    { std::cout &lt;&lt; &quot;caught my_exception: &quot; &lt;&lt; ex.what() &lt;&lt; std::endl; }
  catch ( const std::exception &amp; ex )  // catch #2
    { std::cout &lt;&lt; &quot;caught std::exception: &quot; &lt;&lt; ex.what() &lt;&lt; std::endl; }

  std::cout &lt;&lt; &quot;exiting program&quot; &lt;&lt; std::endl;
  return 0;
}</pre>
</blockquote>
<p>When invoked with no arguments, the output is:</p>
<blockquote>
<pre>starting thread
starting thread function
normal return from thread function
calling join
exiting program</pre>
</blockquote>
<p>Invoked with any argument, the output is:</p>
<blockquote>
<pre>starting thread
starting thread function
calling join
caught my_exception: &quot;what-string&quot;
exiting program</pre>
</blockquote>

<h2><a name="Acknowledgements">Acknowledgements</a></h2>

<p>Alisdair Meredith suggested the mixin approach rather than changing <code>std::exception</code>, and 
also provided an 
alternative approach that did not require changes to exception classes (but did 
require changes to code throwing exceptions.) Peter Dimov and Howard Hinnant 
provided helpful comments to the original paper.</p>

<h2>Revision <a name="History">History</a></h2>

<p>This paper is a major revision of
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2061.html">
N2061</a>.</p>

<hr>
<p> Copyright Beman Dawes 2006</p>

</body>

</html>
