    <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  :: Exceptions - The Details</title>
        <link>https://members.accu.org/index.php/articles/513</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 #34 - Oct 1999</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/c170/">34</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+170/">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;Exceptions - The Details</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 October 1999 17:50:54 +01:00 or Tue, 26 October 1999 17:50:54 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>This is the second part of a three-part series of articles
describing C++ exceptions. In this part we deal with:-</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Special functions</p>
</li>
<li>
<p>Exception specifications</p>
</li>
<li>
<p>Function try blocks</p>
</li>
<li>
<p>std::nothrow</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e35" id="d0e35"></a>Special
functions</h2>
</div>
<p>The exception handling mechanism relies on two functions,
terminate() and unexpected(), for coping with errors related to the
exception handling mechanism itself.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e40" id="d0e40"></a>void
terminate()</h3>
</div>
<p>The function std::terminate() is called:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>If an exception is thrown but not caught.</p>
</li>
<li>
<p>If the exception handling mechanism finds that the stack is
corrupted.</p>
</li>
<li>
<p>If a destructor propagates an exception during stack unwinding
due to another exception (i.e. if a destructor throws while
uncaught_exception() is true).</p>
</li>
</ul>
</div>
<p>The function terminate() calls teminate_handler() which by
default calls abort(). The behaviour of terminate() can be altered
by supplying a function pointer to set_terminate().</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e57" id="d0e57"></a>void
unexpected()</h3>
</div>
<p>If a function throws an exception not allowed by its exception
specification (see below) then:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>the stack is unwound for the function</p>
</li>
<li>
<p>the function unexpected() is called.</p>
</li>
</ul>
</div>
<p>The function unexpected() calls unexpected_handler() which by
default calls terminate(). The behaviour of unexpected() can be
altered by supplying a function pointer to set_unexpected().</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e71" id="d0e71"></a>bool
uncaught_exception()</h3>
</div>
<p>The function uncaught_exception() returns true from the point
where the throw expression has been evaluated until the
exception-declaration of a matching handler is constructed, or if
the code enters unexpected(). uncaught_exception() has rather
sinister uses which will be explained next month.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e76" id="d0e76"></a>Exception
specifications</h2>
</div>
<p>Exception specifications are a way of specifying which
exceptions a function may directly or indirectly throw in the
function declaration. For example:</p>
<pre class="programlisting">
void f() throw (NoLatteException);
void (*fp)() throw (NoCookiesException);
</pre>
<p>If a virtual function has an exception-specification, then any
function that overrides the virtual function shall only allow
exceptions listed, or exceptions derived from those listed. This is
called the co-variant rule.</p>
<pre class="programlisting">
struct X { .. };
struct Y { .. };

struct B {
   virtual void f() throw( X );
   virtual void g();
}

struct C : B {
   void f() throw ( X, Y );  // error
   void g() throw ( Y );     // fine
}
</pre>
<p>A function with no exception-specification is allowed to throw
any exception. A function with the empty exception specification,
throw(), is not allowed to throw any exceptions.</p>
<pre class="programlisting">
void f() throw();     // no exceptions
</pre>
<p>If an exception is thrown that is not allowed by a function's
exception-specification, then unexpected() is called.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e93" id="d0e93"></a>Exception
specifications: to use, or not to use</h2>
</div>
<p>Exception specifications are a way of specifying at the point of
declaration, which exceptions may thrown by this function.</p>
<pre class="programlisting">
struct X { .. );
struct Y { .. };

struct Thing
{
    void a();                // 1
    void b() throw (X);      // 2
    void c() throw (X, Y);   // 3
    void d() throw();        // 4
}
</pre>
<p>A function that has no throw specification (such as on line 1),
is allowed to propagate any exception.</p>
<p>The function on line 2 is only allowed to propagate exceptions
of type X.</p>
<p>The function on line 3 is only allowed to propagate exceptions
of type X and Y.</p>
<p>The function on line 4 is not allowed to propagate exceptions of
any kind.</p>
<p>Note the careful use of the word propagate here; the functions
may throw disqualified exceptions, but they are expected to catch
them before they escape. So, what happens if a function throws an
exception that its specification disallows? Does the program fail
to compile in the first place, or get nasty.</p>
<p>The answer is, of course, the program gets nasty; it calls
<tt class="function">unexpected()</tt>.</p>
<p>Exception handling is a robust method for handling (distantly)
reported errors. Consider the function:</p>
<pre class="programlisting">
void f( int ) throw( a, b, c );
Exception specifications look very useful on the surface, and they are definitely useful as self documentation.  But let's go back to why we have exceptions in C++&hellip;
</pre>
<p>If an exception that is not on the list is thrown, the default
action is to terminate the program. That doesn't sound very robust.
To correctly use exceptions specifications, you must include
everything that can be thrown by any called function (direct or
indirect). Since the primary usefulness of exceptions is to handle
reported errors which may be far down the code calling chain, this
means every function between the throw and the handler must specify
the exception. This is pollution!</p>
<p>Exception specifications are hard to maintain, and carry serious
(counterproductive) side-effects if not 100% correct.</p>
<p>Using throw() everywhere is another mistake people often fall
into. Using this doesn't prevent exceptions being thrown, it merely
tells the compiler that it shouldn't. If the function does, then
it's terminate() time.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>Taligent engineers use exception specifications only with an
architect's approval.</p>
<p class="citetitle c2">Taligent's Guide to Designing Programs</p>
</blockquote>
</div>
<p>And there's a further problem; exception specifications and
templates don't mix.</p>
<p>At the JACC'99, Mike Ball of Sun Microsystems said &quot;Every
language contains a few experiments that didn't work out; finalize
is one for Java.&quot; Well it looks like exception specifications could
be one for C++.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e135" id="d0e135"></a>Special
uses</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e138" id="d0e138"></a>Function-try
blocks</h3>
</div>
<p>What is the difference between:</p>
<pre class="programlisting">
void f(int ii)
{
   try 
   {
       // whatever
   }
   catch (...)
   {
       // stuff
   }
}
</pre>
<p>and:</p>
<pre class="programlisting">
void f(int ii)
try
{
       // whatever
}
catch (...)
{
       // stuff
}
</pre>
<p>The answer is nothing, unless the function is a constructor or a
destructor.</p>
<pre class="programlisting">
C::C(int ii, double id)
try
    : I(f(ii)), d(id)
{
    // rest of ctor
}
catch (...)
{
    // catches errors thrown 
    // from ctor body and 
    // member initialisation list
}
</pre>
<p>Now with the function-try-block, the member initialisation list
is inside the try block. And for the destructor&hellip;</p>
<pre class="programlisting">
C::~C()
try
{
    // rest of dtor
}
catch (...)
{
    // catches errors thrown 
    // from dtor body
    // and member resources
    // released by class C.
}
</pre>
<p>The other style of try-catch would have exited the handler
before the destructors for the members of C were called. Note that
this means we can now promise and guarantee a destructor will not
throw:</p>
<pre class="programlisting">
C::~C() throw()
try
{
    // stuff
}
catch (...)
{
    // stuff, if anything!
}
</pre>
<p>Since the function-try-block was a late addition to the C++
Standard, few compilers support this yet.</p>
<p>Also covered in :-</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>C++ Programming Language 14.4.6.1</p>
</li>
<li>
<p>C++ Primer 19.2.7</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e172" id="d0e172"></a>New -
std::nothrow</h2>
</div>
<p>The C++ standard has ratified a change to the new operator.</p>
<pre class="programlisting">
T *p = new T;
</pre>
<p>Previously, if the call to new above failed, a null pointer
would've been returned. Under the ISO C++ Standard, an exception of
type <tt class="exceptionname">std::bad_alloc</tt> is thrown. It is
possible to suppress this behaviour in favour of the old style by
using the <tt class="literal">nothrow</tt> version.</p>
<pre class="programlisting">
T *p = new (std::nothrow) T;
</pre>
<p>A further interesting question is, if you don't have enough
resources to allocate a request for memory, do you expect to have
enough to be able to deal with it? Most operating systems will have
slowed to be unusable long before the exception gets thrown.</p>
<p>In these extreme cases, exceptions give you the chance to
perform a graceful shutdown even if you can't remedy the
situation.</p>
<p>In the final article of this series I shall offer some best
practice guidance for making use of C++ exceptions.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
