    <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 - Guidance</title>
        <link>https://members.accu.org/index.php/journals/505</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #35 - Jan 2000 + Programming Topics</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/journals/">All</a>

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c169/">35</a>
                    (8)
<br />

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

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

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

                                            <a href="https://members.accu.org/index.php/journals/c169-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c169+65/">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 - Guidance</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 January 2000 16:50:55 +00:00 or Wed, 26 January 2000 16:50:55 +00: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 third and final part of my article on exceptions. In
this part we deal with:-</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Dangers of exceptions</p>
</li>
<li>
<p>Standard Library exceptions</p>
</li>
<li>
<p>Guidelines.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e32" id="d0e32"></a>The
dangers</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e35" id="d0e35"></a>Lost
resources</h3>
</div>
<p>Resource recovery is important in the face of errors. An
acquired resource can easily be lost during stack unwinding unless
it was acquired automatically (that is to say, not as a pointer).
However, it is a common idiom in C++ to acquire resources by
pointer.</p>
<p>To be exception safe, pointers, resource handles, important
state variables (for example a &quot;top of stack&quot; if you're
implementing a stack template class) need special attention. It's
possible to provide that attention with specially written
<tt class="literal">try(){&hellip;} catch()</tt> clauses. It is
much easier to rely on C++'s constructor / destructor
mechanism.</p>
<pre class="programlisting">
void f(const char *filename)
{
  FILE *f = fopen(filename, &quot;r&quot;);
  try {
    // use f
    fclose(f);
  }
  catch (...) {
    fclose(f);
    throw;  // rethrow the exception
  }
}
</pre>
<p>In the above example, the resource (file) is acquired, then
used. An exception may be thrown (not necessarily by the file
specific code), so a handler is present to clean up the mess. This
seems reasonable enough, but what happens if we have a lot of
resources in one function? (critical sections, files, locks,
events). It clearly gets too messy.</p>
<p>This is changing in the face of exceptions. Smart pointers are
classes which acquire the resource pointer in the constructor, and
safely release in the destructor. The pointer is accessed through
an overloaded member access operator, or custom conversion.</p>
<pre class="programlisting">
class File_ptr {
public:
  File_ptr(const char* name, 
              const char *mode )
  { fp = fopen(name, mode);}
  ~File_ptr() {fclose( fp); }
  operator FILE*(){return fp;} 
private:
  FILE *fp;
  // not implemented
  File_ptr( const File_ptr&amp; );
  File_ptr&amp; operator=(const File_ptr&amp; );
}
</pre>
<p>Now we use the atomic variable of class <tt class=
"classname">File_ptr</tt> where we would've used a pointer to
<tt class="type">FILE</tt>. In the case of an exception occurring
before the <tt class="classname">File_ptr</tt> goes out of scope,
stack unwinding takes care of the cleanup for you - you don't need
special exception handlers for every resource.</p>
<p>For pointers created and destroyed by new and delete, STL
provides the <tt class="classname">auto_ptr&lt;&gt;</tt> template.
The resources can be allocated when the object is constructed (this
is optional), the resources will be released when the object is
deleted. (Note - consult your system documentation about the
precise behaviour of <tt class=
"classname">auto_ptr&lt;&gt;</tt>).</p>
<p>The idiom of wrapping a raw pointer with an object to control
its initialisation and release is called &quot;resource acquisition is
initialisation&quot;, and is covered on the QA Training Advanced C++
course, in Scott Meyers' &quot;More Effective C++&quot; (Item 9), and in
Bjarne Stroustrup's &quot;The C++ Programming Language&quot; (14.4), where
the phrase was coined.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e74" id="d0e74"></a>Catching
exceptions; by value, pointer or reference</h3>
</div>
<p>Exceptions can be expensive to throw. Consider the difference
between the following handlers:</p>
<pre class="programlisting">
Thing t;
try {
  throw t;          // 1
}
catch (Thing x){    // 2
  throw;
}
catch (Thing&amp; x){    // 3
  // whatever
}
</pre>
<p>At point 1, a temporary copy of the local object is thrown, not
the local object itself. The copy is necessary to extend the
exception's lifetime until a handler has completed. The cost of
this copy is one copy constructor.</p>
<p>The handler at point 2 catches by value; a copy is made of the
thrown exception object. The cost of this is another copy
constructor.</p>
<p>The handler at point 3 catches by reference; no copy is
made.</p>
<p>Another reason not to catch by value is that of polymorphism.
Consider this:</p>
<pre class="programlisting">
class A { /* .. */ };
class B : public A { /* .. */ };

void f() {
  try {
    throw B;
  }
  catch (A a)    { // #
    throw a;    // $
  }
}
</pre>
<p>At the point #, the exception object has been caught by value of
type A (base class of the originally thrown type, B). At the point
$, the exception is rethrown, except, the exception thrown now is
of type A - we've lost our derived class information!</p>
<p>There is a good argument against throwing a pointer too. Should
the handler delete the pointer? Clearly, catching by reference, or
preferably const-reference is the best way of handling
exceptions.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e95" id="d0e95"></a>Destructors</h3>
</div>
<p>Destructors are called in three situations:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>when the object goes out of scope or is deleted.</p>
</li>
<li>
<p>during the stack unwinding mechanism of exception handling.</p>
</li>
<li>
<p>by explicit call (rare).</p>
</li>
</ul>
</div>
<p>Therefore, there may or may not be an exception active when a
destructor is called. If another exception is thrown whilst an
exception is already active, the program calls <tt class=
"function">terminate()</tt>. This is not an acceptable outcome if
you've decided to use exceptions to manage your programs (and
exceptions have to be considered right through your code when you
use them - no half measures).</p>
<p>There are two solutions to this situation:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>use <tt class="function">uncaught_exception()</tt> in the
destructor to determine if an exception is active, and only throw
if there isn't, or</p>
</li>
<li>
<p>never throw exceptions from destructors.</p>
</li>
</ol>
</div>
<p>On the surface the first option may seem fine, but as Steve
Clamage put it: &quot;<span class="quote">My question is why would it be
good design to throw the exception only sometimes, and if you can
sometimes get along without throwing it, why not always get along
without throwing it?</span>&quot; - Steve Clamage, Sun Microsystems.</p>
<p>The only reasonable solution is never throw from destructors.
This guideline is supported by all major commentators.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e134" id=
"d0e134"></a>Constructors</h3>
</div>
<p>What? You mean they got constructors too? Well, if you've been
paying attention so far, the intricacies of exceptions from
constructors shouldn't be a problem to you.</p>
<p>The C++ Standard (15.2.2 [except.ctor]) says, &quot;An object that is
partially constructed or partially destroyed will have destructors
executed for all of its fully constructed subobjects&hellip;&quot;.</p>
<p>If you've wrapped your resources with smart pointers, this
shouldn't be a problem, right?</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e143" id="d0e143"></a>The overhead
associated with exceptions</h3>
</div>
<p>Exception handling (like all error-handling code) comes with
costs. Programs will be slower and of a larger size when using
exceptions; they have a lot more bookkeeping to do. Having
try-blocks in your program may increase your code size and runtime
cost by 5-10% (source: More Effective C++). To minimise this, avoid
unnecessary try-blocks.</p>
<p>Exception specifications add a similar cost, but since we're not
using those, that doesn't matter.</p>
<p>So how much of a hit do we take when we actually throw an
exception? The best answer we can give is &quot;a big one&quot;. Meyers
suggests returning from a function by throwing an exception could
cost up to three times what it does when returning normally. My own
test with MS VC++ 5 showed a fourfold increase in run time.</p>
<p>This overhead will come down in time. In any case, for most
programs it's more important to get the correct answer a bit
slower, than to get the wrong answer fast. It is even conceivable
that code with exception handling constructs could execute faster
than old style error handling code, since a lot of if-else style
constructs could be removed.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e154" id="d0e154"></a>Standard library
exceptions</h3>
</div>
<p>The standard C++ library defines a base class for the types of
objects thrown as exceptions by C++ Standard library components in
the header <tt class="filename">&lt;exception&gt;</tt>:</p>
<pre class="programlisting">
namespace std {
    class exception {
 public:
  exception() throw();
  exception(const exception&amp;) throw();
  exception&amp; operator=(const exception&amp;)
            throw();
  virtual ~exception() throw();
  virtual const char* what() const
            throw();
 };
}
</pre>
<p>The class <tt class="classname">bad_exception</tt> is also
defined in <tt class="filename">&lt;exception&gt;</tt>. This
exception is thrown when an exception specification has been
compromised, but the exception specification allows exceptions of
type <tt class="classname">bad_exception</tt> to be thrown.
<tt class="function">std::unexpected()</tt> performs the necessary
remapping.</p>
<p>The following standard exceptions are defined in the header
<tt class="filename">&lt;stdexcept&gt;</tt>:</p>
<pre class="programlisting">
logic_error
  domain_error
  invalid_argument
  length_error
  out_of_range
</pre>
<p>(the indented classes are publicly derived from <tt class=
"classname">logic_error</tt>).</p>
<pre class="programlisting">
runtime_error
  range_error
  overflow_error
  underflow_error
</pre>
<p>(the indented classes are publicly derived from <tt class=
"classname">runtime_error</tt>).</p>
<p>A <tt class="classname">logic_error</tt> is an error that is
detectable in the logic of the code. A <tt class=
"classname">runtime_error</tt> is one that is not detected in the
logic of the code.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e205" id="d0e205"></a>Guidelines
for efficient exceptions</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e208" id="d0e208"></a>Do</h3>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>catch by reference (or const reference) (8.2)</p>
</li>
<li>
<p>use the &quot;resource acquisition is initialisation&quot; idiom (8.1)</p>
</li>
<li>
<p>use exceptions only for exceptional circumstances, where other
error handling techniques won't suffice</p>
</li>
<li>
<p>treat exceptions as another area of program design</p>
</li>
<li>
<p>make constructors &amp; destructors exception safe using
function try blocks (7.1)</p>
</li>
</ul>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e227" id="d0e227"></a>Don't</h3>
</div>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>throw from destructors (8.3)</p>
</li>
<li>
<p>use exception specifications without serious justification
(6.1)</p>
</li>
<li>
<p>use exceptions as an alternative control structure</p>
</li>
<li>
<p>flood your code with try-catch-throws</p>
</li>
</ul>
</div>
<p>Thanks to Francis Moore, Ian Bruntlett, Jon Jagger and Jim Barry
for your comments.</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e245" id="d0e245"></a>Further
reading</h2>
</div>
<div class="bibliomixed">
<p class="bibliomixed"><span class="citetitle"><i class=
"citetitle">The C++ Programming Language Third Edition</i></span>
Bjarne Stroustrup (Addison-Wesley, 1997)</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed"><span class="citetitle"><i class=
"citetitle">More Effective C++</i></span> Scott Meyers
(Addison-Wesley 1996)</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed"><span class="citetitle"><i class=
"citetitle">The ISO/IEC C++ Language Standard
(14882-1998)</i></span> (ISO/IEC 1998)</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed"><span class="citetitle"><i class=
"citetitle">Exception Handling: A False Sense of
Security</i></span> Tom Cargill (C++ Report, Volume 6, Number 9,
Nov-Dec 1994)</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed"><span class="citetitle"><i class=
"citetitle">Taligent's Guide to Programming Taligent</i></span>
(Addison-Wesley, 1995)</p>
</div>
<div class="bibliomixed">
<p class="bibliomixed"><span class="citetitle"><i class=
"citetitle">Counting Object in C++</i></span> (Sidebar: Placement
new and placement delete) Scott Meyers (C/C++ Users Journal, April
1998) Downloadable from <span class="bibliomisc"><a href=
"http://meyerscd.awl.com/" target=
"_top">http://meyerscd.awl.com/</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
