    <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 Basics</title>
        <link>https://members.accu.org/index.php/articles/524</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 #33 - Aug 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/c171/">33</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+171/">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 Basics</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 August 1999 17:50:54 +01:00 or Thu, 26 August 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 start of a 3-part series of articles describing C++
exceptions. In this part we deal with:-</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Error handling &amp; exceptions</p>
</li>
<li>
<p>Throwing exceptions</p>
</li>
<li>
<p>Handling Exceptions</p>
</li>
<li>
<p>Exception Remapping</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e35" id="d0e35"></a>Error
handling</h2>
</div>
<p>Code has two error-related responsibilities; handling errors
detected elsewhere (for example input errors from stream
libraries), and reporting errors that cannot be dealt with here
(for example file access permissions).</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/Cornish%20-%20Exceptions%201.png" align="middle"></div>
<p>Traditional techniques for dealing with errors that cannot be
dealt with locally are:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>terminate the program</p>
</li>
<li>
<p>return a value representing an error</p>
</li>
<li>
<p>return a legal value and pretend nothing happened</p>
</li>
<li>
<p>call a predefined error function</p>
</li>
<li>
<p>ignore the error</p>
</li>
</ol>
</div>
<p>The first option, to terminate the program, is useless and rude.
Usually no one should have to tolerate that kind of behaviour from
software. For some standalone systems, though, having the program
restarted is the best response to a program failure.</p>
<p>The second option, to return a value representing an error is
what most people would think of as an acceptable strategy. However,
it appears that the more frequently a function is used (without
error), the more complacent programmers get about checking the
return value. For example, who checks the return of <tt class=
"methodname">printf()</tt>? <tt class="classname">stdout</tt> can
be redirected to a hard disk file, and hard disks can fill up!</p>
<p>The third option (return a legal value, and pretend nothing
happened) is evil on a par with the first option. The calling
function has no knowledge that something went wrong, and so cannot
take measures to correct it. The error continues to exist in the
program's state until either the program falls over in a molten
mass, or provides incorrect results seemingly at random. This
shouldn't ever get past testing stages.</p>
<p>The fourth option seems the most reasonable choice, but what
would a specified error handling function be able to do after
logging the error? See the other options&hellip;</p>
<p>The last option is similar to the second, but you just don't
care about errors. No database handle? Just access the records
anyway! Don't expect to see release 2.0.</p>
<p>Due to the increasing popularity of libraries, components and
distributed architectures, we now have common situations where the
traditional techniques of error handling are all inadequate. This
is where errors propagate from &quot;distances&quot; (for example across
library boundaries or deep inside code). As an example, Company A
writes a library that Company B wants to use. The library reports
errors and failures, but there is no way to force Company B's
programmers to check the return values for errors. Or at least
there wasn't. Exceptions cannot be ignored in the same way that a
burning juggernaught cannot be ignored.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e77" id="d0e77"></a>So what is an
exception?</h2>
</div>
<p>Exceptions in C++ are alternatives to the traditional methods of
dealing with errors.</p>
<p>Exceptions came about because library writers know how to detect
errors, but don't know what to do with them, and users know how to
deal with them, but don't know how to detect them. This paradox is
solved by the way that exceptions separate error reporting and
error handling. The exception is used to help deal with error
reporting. Error handling is dealt with by the
exception-handler.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>C++ exceptions were designed to be most useful when an
unexpected error occurs at a significant distance from any code
that can possibly handle it. (Steve Clamage, Sun Microsystems)</p>
</blockquote>
</div>
<p>If you are a C programmer, think of exceptions as an OO-friendly
<tt class="function">longjmp()</tt> that takes care of stack
unwinding for you.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e92" id="d0e92"></a>Throwing
exceptions</h2>
</div>
<p>To report the error, you <span class="bold"><b>throw</b></span>
an exception. An exception is usually an object (instance of class
/ struct) encapsulating appropriate state information for the
error. Using built in types for exceptions is possible, but not
recommended (how would you discriminate between exception types if
both you and a library's author had used <tt class="type">int</tt>
as an exception type?). The type of the object should reflect the
type of the error. For example, out_of_bounds.</p>
<p>In the event of an error, the program can construct the
exception object and report the error by throwing it. For
example:</p>
<pre class="programlisting">
const int array::integerAt(size_t index) const
{
   if ( index &gt;= (this-&gt;size()) )
   {
      throw out_of_bounds(&quot;Bad Index&quot;);
   }
   // otherwise return requested index
   return ...;
}
</pre>
<p>If the exception type is a class, it must have an accessible
copy-constructor (or default copy-constructor). Otherwise the
program is ill-formed (i.e. shouldn't compile).</p>
<p>The throw expression initialises a temporary object of the type
specified in the expression (with differences - arrays and
functions are changed to pointers, and const-volatile qualifiers
(<span class="emphasis"><em>cv-qualifiers</em></span>) are
removed). The temporary exists as long as there is a handler being
executed for this exception. In the case where the exception is
rethrown, the exception is reactivated with the existing temporary
object.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e114" id="d0e114"></a>Handling an
exception</h2>
</div>
<p>A function can indicate that it is willing to catch exceptions
of certain types by declaring a try-catch block. For example:</p>
<pre class="programlisting">
try
{
    // code which may throw
    // an exception
}

catch ( range_error&amp; )
{
    cerr &lt;&lt; &quot;oops!&quot; &lt;&lt; endl;
}
</pre>
<p>The catch block is called the exception handler. It can only be
used immediately after a try block, or after another catch attempt.
So if any code in a try block (or code called from a try block)
throws an exception, the handlers will be examined to see if they
are willing to handle the exception.</p>
<p>Throwing an exception transfers control to a handler. An object
is created and the type of that object determines which handlers
can catch it. For example, consider the following:</p>
<pre class="programlisting">
try 
{
    throw NoNachos;
}
catch ( OutOfFood&amp; )
{
    // caught here? - 1
}
catch ( NoNachos&amp; )
{
    // or here? - 2
}
catch ( NoCola&amp; )
{
    // or caught here? - 3
}
</pre>
<p>With no further information, we assume the exception is caught
in the second handler. However, if NoNachos is part of an
inheritance hierarchy like this:</p>
<pre class="programlisting">
class OutOfFood {..};
class NoNachos : public OutOfFood {..};
class NoCola : public OutOfFood {..};
class NoIceCream : public OutOfFood {..};
</pre>
<p>In this case, handler 1 would be the first matching handler for
the NoNachos since OutOfFood is an unambiguous base class of
NoNachos.</p>
<p>The following table summarises when a handler matches a throw
expression with an object of type E.</p>
<div class="informaltable">
<table border="1" cellspacing="0">
&lt;colgroup&gt;
&lt;col&gt;
&lt;col&gt;&lt;/colgroup&gt;
&lt;thead&gt;
<tr>
<th>Handler type</th>
<th>Matching exception type</th>
</tr>
&lt;/thead&gt;
&lt;tbody&gt;
<tr>
<td>Cv T or cv T&amp;</td>
<td>E and T are the same type (ignoring cv-qualifiers)</td>
</tr>
<tr>
<td>Cv T or cv T&amp;</td>
<td>T is an unambiguous public base class of E</td>
</tr>
<tr>
<td>Cv1 T* cv2</td>
<td>
<div class="literallayout">
<p>E is a pointer type that can be converted <br>
to the handler type by<br>
<br>
a standard pointer conversion<br>
a qualification conversion</p>
</div>
</td>
</tr>
&lt;/tbody&gt;
</table>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e160" id="d0e160"></a>Catch
all</h2>
</div>
<p>catch(&hellip;) specifies a match for any exception. Since
exception handlers are tried in order of appearance, this handler
ought to be the last handler for its try block to avoid &quot;hiding&quot;
the other handlers. The compiler should issue a diagnostic if you
have handlers after the catch all.</p>
<pre class="programlisting">
try 
{
    // stuff
}
catch ( exception1 &amp;e1 )
{
    // handle exception1
}
catch ( exception2 &amp;e2 )
{
    // handle exception2
}
catch ( exception3 &amp;e3 )
{
    // handle exception3
}
catch (...)
{
    // generic handler
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e167" id="d0e167"></a>Stack
unwinding</h2>
</div>
<p>If no handlers are found immediately following the try-block,
the stack is unwound to the next enclosing try block, and these
handlers are checked for a match. As control passes from the
throw-expression to the handler, destructors are called for all
automatic objects constructed since the (current) try block was
entered. The automatic objects are destroyed in reverse order of
their construction. This is known as <span class="bold"><b>stack
unwinding</b></span>. This can cause problems if references and
pointers are used to acquire resources.</p>
<pre class="programlisting">
int main()
{
    try 
    {
       f(&quot;file.txt&quot;, &quot;r&quot;);
    }
    catch(...)
    {
       cerr &lt;&lt; &quot;Problem with file&quot; 
            &lt;&lt; endl;
    }
    return 0;
}

void f(const char *name,
       const char *mode)
{
   FILE *fp = fopen(name, mode);
   char *buf = new (nothrow) char[4096];
         // parse file etc - #
   delete[] buf;
   fclose( fp );
}
</pre>
<p>Ignore for now the (<tt class="literal">nothrow</tt>)- this will
be explained next month. In the above example, the function
<tt class="function">f()</tt> takes a filename and file open mode,
and parses the file. However, if the code in # were to throw, the
stack would be unwound to the beginning of the enclosing try-block
(in main). This means that <tt class="varname">fp</tt> and
<tt class="varname">buf</tt> go out of scope without having their
resources released. Hence we have potential resource leaks.</p>
<p>What if we had a class to hold the file as a collection of
lines:</p>
<pre class="programlisting">
class FileInspect
{
    class Line { /* &hellip; */ };
    Line *lines[];
    // other details
public:
    FileInspect()
       { lines = new Line[4096]; }
    ~FileInspect() { delete[] lines; }
    // other details
}
</pre>
<p>and we redefined function f() above as:</p>
<p>void f(const char *name, const char *mode) { FILE *fp =
fopen(name, mode); FileInspect ft; // parse file etc - # delete[]
buf; fclose( fp ); }</p>
<p>Suppose again, that at some point of parsing the file, an
exception occurs at the point #. This time, the <tt class=
"literal">FILE* fp</tt> is the only resource lost, because
FileInspect <tt class="varname">ft</tt> is an atomic variable. Or
is this not the case?</p>
<p>The destructor of FileInspect calls <tt class=
"literal">delete[]</tt> lines which causes the destructor for the
Line object to be called 4096 times. It wouldn't be unfeasible for
<tt class="methodname">Line::~Line</tt> to throw an exception
(after all, a line buffer was in use when the first exception was
thrown). So which exception takes precedence? The answer is far
more horrible than you can imagine: neither.</p>
<p>If a destructor called during stack unwinding throws an
exception (without handling it itself), <span class=
"bold"><b>terminate()</b></span> is called (see the section on
special functions next month). Therefore, it is good practise
<span class="emphasis"><em>not to throw exceptions in
destructors</em></span> (indeed, no destructor in the C++ library
throws). See the section on Exception Specifications next month for
a common misconception on preventing exceptions.</p>
<p>So, what happens if no matching handler exists in any
surrounding try-block? If an uncaught exception propagates out of
main(), the terminate function is called (again, see the section on
special functions next month).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e225" id="d0e225"></a>Nested
try-blocks</h2>
</div>
<p>Try-catch blocks can be nested. Should you feel dark needs,
goto, break, return and continue can be used to transfer control
out of a try block. They cannot transfer control into one,
however.</p>
<pre class="programlisting">
try
{
    GetNachos();
}
catch (const NoNachos &amp;nn)
{
    // no nachos - lets get Ben &amp; Jerrys
    // default is &quot;Cherry Garcia&quot; flavour
    try 
    {
        GetIceCream();
    }
    catch (const NoIceCream &amp;nic)
    {
        // deal with no ice-cream
    }
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e232" id=
"d0e232"></a>Rethrowing</h2>
</div>
<p>A throw expression with no operand rethrows the current
exception being handled. If no exception is being handled, throw
calls terminate(). A rethrown exception is no longer considered to
be caught. An exception is considered finished when the
corresponding catch clause exists (or when unexpected() exists
after being entered due to a throw - see special functions for
details on <tt class="function">unexpected()</tt>). In this
situation, the exception is reactivated with the <span class=
"bold"><b>existing</b></span> temporary.</p>
<pre class="programlisting">
FILE* fp = fopen(&quot;filename.txt&quot;, &quot;r&quot;);
try 
{
    UseFile(fp);
    fclose(fp);
}

catch (...)
{
    fclose(fp);  // close file
    throw;       // rethrow original
                 // exception
}
</pre>
<p>Here an exception has occurred. We don't want to handle it here,
but we can't leak the file resource. So we catch the exception,
close the file, and rethrow it to be handled elsewhere.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e247" id="d0e247"></a>Exception
remapping</h2>
</div>
<p>In a layered architecture, each layer may have its own
exceptions, and each exception will (probably) only have context
within that layer. For example, an exception which represents a
low-level parity error on byte 2 packet 15 is probably not much use
at the user interface layer, unless it has been washed, shaved,
dressed and presented to the users as a &quot;Data transfer error&quot;. Even
though the error has not been dealt with, it has been changed to a
different guise to make it acceptable to a different layer.</p>
<p>Consider the situation where you are using a third party library
with their own exception classes.</p>
<pre class="programlisting">
/**** third party code ****/
void Obscure() 
      throw (UglyDucklingException);
</pre>
<pre class="programlisting">
/**** your code ****/
void UsefulFunction()
      throw (BeautifulSwanException)
{
  try
  {
     ..
     Obscure()
  }
  catch (UglyDucklingException &amp;ude)
  {
     throw BeautifulSwanException(ude);
  }
}
</pre>
<pre class="programlisting">
/**** client code ****/
try 
{
    UsefulFunction();
}
catch (const BeautifulSwanException &amp;e)
{
    // everyone's happy
}
</pre>
<p>The function UsefulFunction() attempts to use the third party
function Obscure() which may throw an exception you don't want
exposed to clients who use your software. The call to Obscure() is
in a try block which catches the ugly UglyDucklingException
exception. The handler then throws an instance of
BeautifulSwanException, which you are happy to let clients deal
with. The UglyDucklingException is considered handled, and the only
exception to propagate from the function is the
BeautifulSwanException.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
