    <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  :: Error and Exception Handling</title>
        <link>https://members.accu.org/index.php/journals/332</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 #57 - Oct 2003 + 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/c155/">57</a>
                    (12)
<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/c155-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c155+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;Error and Exception Handling</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 October 2003 22:56:14 +01:00 or Thu, 02 October 2003 22:56:14 +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="d0e16" id="d0e16"></a>When should I
use exceptions?</h2>
</div>
<p>The simple answer is: &quot;whenever the semantic and performance
characteristics of exceptions are appropriate.&quot;</p>
<p>An oft-cited guideline is to ask yourself the question &quot;is this
an exceptional (or unexpected) situation?&quot; This guideline has an
attractive ring to it, but is usually a mistake. The problem is
that one person's &quot;exceptional&quot; is another's &quot;expected&quot;: when you
really look at the terms carefully, the distinction evaporates and
you're left with no guideline. After all, if you check for an error
condition, then in some sense you expect it to happen, or the check
is wasted code.</p>
<p>A more appropriate question to ask is: &quot;do we want stack
unwinding here?&quot; Because actually handling an exception is likely
to be significantly slower than executing mainline code, you should
also ask: &quot;Can I afford stack unwinding here?&quot; For example, a
desktop application performing a long computation might
periodically check to see whether the user had pressed a cancel
button. Throwing an exception could allow the operation to be
cancelled gracefully. On the other hand, it would probably be
inappropriate to throw and handle exceptions in the inner loop of
this computation because that could have a significant performance
impact. The guideline mentioned above has a grain of truth in it:
in time critical code, throwing an exception should be the
exception, not the rule.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e25" id="d0e25"></a>How should I
design my exception classes?</h2>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>Inherit from <tt class="classname">std::exception</tt>. Except
in very rare circumstances where you can't afford the cost of a
virtual table, <tt class="classname">std::exception</tt> makes a
reasonable exception base class, and when used universally, allows
programmers to catch &quot;everything&quot; without resorting to <tt class=
"literal">catch(...)</tt>. For more about <tt class=
"literal">catch(...)</tt>, see below.</p>
</li>
<li>
<p>Don't embed a <tt class="classname">std::string</tt> object or
any other data member or base class whose copy constructor could
throw an exception. That could lead directly to <tt class=
"methodname">std::terminate()</tt> at the throw point. Similarly,
it's a bad idea to use a base or member whose ordinary
constructor(s) might throw, because, though not necessarily fatal
to your program, you may report a different exception than intended
from a throw-expression that includes construction such as:</p>
<pre class="programlisting">
throw some_exception();
</pre>
<p>There are various ways to avoid copying string objects when
exceptions are copied, including embedding a fixed-length buffer in
the exception object, or managing strings via referencecounting.
However, consider the next point before pursuing either of these
approaches.</p>
</li>
<li>
<p>Format the <tt class="function">what()</tt> message on demand,
if you feel you really must format the message. Formatting an
exception error message is typically a memory-intensive operation
that could potentially throw an exception. This is an operation
best delayed until after stack unwinding has occurred, and
presumably, released some resources. It's a good idea in this case
to protect your <tt class="function">what()</tt> function with a
<tt class="literal">catch(...)</tt> block so that you have a
fallback in case the formatting code throws</p>
</li>
<li>
<p>Don't worry too much about the <tt class="function">what()</tt>
message. It's nice to have a message that a programmer stands a
chance of figuring out, but you're very unlikely to be able to
compose a relevant and user-comprehensible error message at the
point an exception is thrown. Certainly, internationalization is
beyond the scope of the exception class author. Peter Dimov makes
an excellent argument that the proper use of a <tt class=
"function">what()</tt> string is to serve as a key into a table of
error message formatters. Now if only we could get standardized
<tt class="function">what()</tt> strings for exceptions thrown by
the standard library...</p>
</li>
<li>
<p>Expose relevant information about the cause of the error in your
exception class's public interface. A fixation on the <tt class=
"function">what()</tt> message is likely to mean that you neglect
to expose information someone might need in order to make a
coherent message for users. For example, if your exception reports
a numeric range error, it's important to have the actual numbers
involved available as numbers in the exception class's public
interface where error reporting code can do something intelligent
with them. If you only expose a textual representation of those
numbers in the <tt class="function">what()</tt> string, you will
make life very difficult for programmers who need to do something
more (e.g. subtraction) with them than dumb output.</p>
</li>
<li>
<p>Make your exception class immune to double-destruction if
possible. Unfortunately, several popular compilers occasionally
cause exception objects to be destroyed twice. If you can arrange
for that to be harmless (e.g. by zeroing deleted pointers) your
code will be more robust.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e93" id="d0e93"></a>What About
Programmer Errors?</h2>
</div>
<p>As a developer, if I have violated a precondition of a library
I'm using, I don't want stack unwinding. What I want is a core dump
or the equivalent - a way to inspect the state of the program at
the exact point where the problem was detected. That usually means
<tt class="function">assert()</tt> or something like it.</p>
<p>Sometimes it is necessary to have resilient APIs which can stand
up to nearly any kind of client abuse, but there is usually a
significant cost to this approach. For example, it usually requires
that each object used by a client be tracked so that it can be
checked for validity. If you need that sort of protection, it can
usually be provided as a layer on top of a simpler API. Beware
half-measures, though. An API which promises resilience against
some, but not all abuse is an invitation to disaster. Clients will
begin to rely on the protection and their expectations will grow to
cover unprotected parts of the interface.</p>
<p>Note for Windows developers: unfortunately, the native
exception-handling used by most Windows compilers actually throws
an exception when you use <tt class="function">assert()</tt>.
Actually, this is true of other programmer errors such as
segmentation faults and divide-by-zero errors. One problem with
this is that if you use JIT (Just In Time) debugging, there will be
collateral exceptionunwinding before the debugger comes up because
<tt class="literal">catch(...)</tt> will catch these not-really-C++
exceptions. Fortunately, there is a simple but little-known
workaround, which is to use the following incantation:</p>
<pre class="programlisting">
extern &quot;C&quot; void straight_to_debugger(
               unsigned int,
               EXCEPTION_POINTERS*) {
  throw;
}

extern &quot;C&quot; void
  (*old_translator)(unsigned,
                    EXCEPTION_POINTERS*)
  = _set_se_translator(
                    straight_to_debugger);
</pre>
<p>This technique doesn't work if the SEH is raised from within a
catch block (or a function called from within a catch block), but
it still eliminates the vast majority of JIT-masking problems.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e115" id="d0e115"></a>How should I
handle exceptions?</h2>
</div>
<p>Often the best way to deal with exceptions is to not handle them
at all. If you can let them pass through your code and allow
destructors to handle cleanup, your code will be cleaner.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e120" id="d0e120"></a>Avoid
<tt class="literal">catch(...)</tt> when possible</h2>
</div>
<p>Unfortunately, operating systems other than Windows also wind
non-C++ &quot;exceptions&quot; (such as thread cancellation) into the C++ EH
machinery, and there is sometimes no workaround corresponding to
the <tt class="literal">_set_se_translator</tt> hack described
above. The result is that <tt class="literal">catch(...)</tt> can
have the effect of making some unexpected system notification at a
point where recovery is impossible look just like a C++ exception
thrown from a reasonable place, invalidating the usual safe
assumptions that destructors and catch blocks have taken valid
steps to ensure program invariants during unwinding.</p>
<p>I reluctantly concede this point to Hillel Y. Sims, after many
long debates in the newsgroups: until all OSes are &quot;fixed&quot;, if
every exception were derived from std::exception and everyone
substituted <tt class="literal">catch(std::exception&amp;)</tt> for
<tt class="literal">catch(...)</tt>, the world would be a better
place.</p>
<p>Sometimes, <tt class="literal">catch(...)</tt>, is still the
most appropriate pattern, in spite of bad interactions with
OS/platform design choices. If you have no idea what kind of
exception might be thrown and you really must stop unwinding it's
probably still your best bet. One obvious place where this occurs
is at language boundaries.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e147" id="d0e147"></a>References</h2>
</div>
<div class="bibliomixed">
<p class="bibliomixed">The following paper is a good introduction
to some of the issues of writing robust generic components: D.
Abrahams: &quot;Exception Safety in Generic Components&quot;, originally
published in M. Jazayeri, R. Loos, D. Musser (eds.): <span class=
"citetitle"><i class="citetitle">Generic Programming, Proc. of a
Dagstuhl Seminar, Lecture Notes on Computer Science</i></span>.
Volume 1766</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
