    <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  :: Handling Exceptions in finally</title>
        <link>https://members.accu.org/index.php/journals/236</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 #62 - Aug 2004 + 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/c150/">62</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/c150-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c150+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;Handling Exceptions in finally</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 August 2004 22:52:10 +01:00 or Sun, 01 August 2004 22:52:10 +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="d0e20" id="d0e20"></a></h2>
</div>
<p>Recently I was reviewing some old Java code that performs SQL
queries against a database and closes the resources in finally
blocks. When I examined the code I realized that the handling of
the resources was flawed if an exception occurred. This article
looks at how the handling of the resources and exceptions was
problematic and some approaches to solving these problems.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>The
Problems</h2>
</div>
<p>The code in question was made up of static methods where each
method used a <tt class="classname">Connection</tt> parameter and
performed the necessary actions to create a query, perform the
query and process the results of the query. My problem came from
the handling of the query and results resources, i.e. the instances
of <tt class="classname">PreparedStatement</tt> and <tt class=
"classname">ResultSet</tt>.</p>
<p>The <tt class="classname">PreparedStatement</tt> and <tt class=
"classname">ResultSet</tt> were created in the main try block of
the method and were closed in the associated finally block. The
<tt class="methodname">close()</tt> method of these classes can
throw a <tt class="exceptionname">SQLException</tt> and in the
<tt class="literal">finally</tt> block each <tt class=
"methodname">close()</tt> method was wrapped in a <tt class=
"literal">try</tt>/<tt class="literal">catch</tt> where the
<tt class="exceptionname">SQLException</tt> was caught and
converted into a <tt class="exceptionname">RuntimeException</tt> to
be thrown. The outline of the original code is shown in the
following listing:</p>
<pre class="programlisting">
public static ArrayList foo(Connection conn)
                        throws SQLException {
  ArrayList results = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {   
    // create a query, perform the query and
    // process the results
  }
  finally {
    try {
      rs.close();
    }
    catch(SQLException ex) {
      throw new RuntimeException(ex);
    }
    try {
      ps.close();
    }
    catch(SQLException ex) {
      throw new RuntimeException(ex);
    }
  }
  return results;
}
</pre>
<p>There are a number of problems with this code:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>If an exception is thrown in the <tt class="literal">try</tt>
block and a subsequent exception is thrown in the <tt class=
"literal">finally</tt> block the original exception is lost.</p>
<p>The problem where an exception is hidden by a subsequent
exception is well known and is discussed in a number of books:
<i class="citetitle">Thinking in Java</i> [<a href=
"#Eckel">Eckel</a>] 'the lost exception', <i class="citetitle">Java
in Practice</i> [<a href="#Warren-">Warren-</a>] and <i class=
"citetitle">Practical Java - Programming Language Guide</i>
[<a href="#Hagger">Hagger</a>] to name a few. All discuss the
problem and I will present a trivial version here with some example
code:</p>
<pre class="programlisting">
public void foo() {
  try {
    throw new RuntimeException(&quot;Really important&quot;);
  }
  finally {
    throw new RuntimeException(&quot;Just trivial&quot;);
  }
}
</pre>
<p>A caller of this function would receive the &quot;Just trivial&quot;
exception, there would be no evidence that the &quot;Really important&quot;
exception ever occurred at all. In the original code if an
exception occurred in the <tt class="literal">finally</tt> block
after a <tt class="exceptionname">SQLException</tt> had been thrown
in the <tt class="literal">try</tt> block, the <tt class=
"exceptionname">SQLException</tt> would be lost.</p>
</li>
<li>
<p>The use of <tt class="exceptionname">RuntimeException</tt>s to
throw the exceptions caught in the <tt class="literal">finally</tt>
block when the method would throw a <tt class=
"exceptionname">SQLException</tt> from the <tt class=
"literal">try</tt> block is inconsistent, <tt class=
"exceptionname">SQLException</tt> should be used for both.</p>
</li>
<li>
<p>If an exception is thrown by the closing of the <tt class=
"classname">ResultSet</tt>, no attempt is made to close the
<tt class="classname">PreparedStatment</tt>, that may cause a
possible resource leak.</p>
</li>
</ol>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e147" id=
"d0e147"></a>Solutions</h2>
</div>
<p>We can fix some of the problems very easily by nesting the
handling of the resources in <tt class=
"literal">try</tt>/<tt class="literal">finally</tt> blocks (as
demonstrated in [<a href="#Griffiths">Griffiths</a>]) and to remove
the conversion to <tt class="exceptionname">RuntimeException</tt>s.
This would be implemented in the method as follows:</p>
<pre class="programlisting">
// assign query to ps
try {   
  // perform the query and assign result to rs
  try {
    // process the results 
  }
  finally { rs.close(); }
}
finally { ps.close(); }
</pre>
<p>This solves the second problem, as the method is already
declared to throw a <tt class="exceptionname">SQLException</tt> no
conversion is required, and the third problem, because even if a
exception is thrown by <tt class="methodname">rs.close()</tt> the
<tt class="methodname">ps.close()</tt> will always be called.</p>
<p>However this leaves the first problem of the lost exception. The
suggested approach in [<a href="#Warren-">Warren-</a>] is to
&quot;<span class="quote">Never let exceptions propagate out of a
finally block</span>&quot;, this would be implemented in the <tt class=
"literal">finally</tt> block as follows:</p>
<pre class="programlisting">
finally {
  try {
    rs.close();
  }
  catch(SQLException ex) {
    /* exception ignored */
  }
  try {
    ps.close();
  }
  catch(SQLException ex) {
    /* exception ignored */
  }
}
</pre>
<p>This approach only solves the hidden exception problem in the
original code but as a consequence adds an additional problem: it
is possible for the <tt class="methodname">rs.close()</tt> to be
the original exception and this is ignored. Ignoring an exception
is likely to make recovery in higher levels of the code more
difficult, if not impossible. It is also likely to mislead a user
trying to determine the cause of a failure; a later related
exception may be mistakenly diagnosed as the source of the problem.
The consequences of ignoring exceptions are discussed further in
[<a href="#Bloch">Bloch</a>] &quot;Item 47: Don't ignore
exceptions&quot;.</p>
<p>[<a href="#Hagger">Hagger</a>] offers a different solution to
this problem by collecting up the exceptions thrown during
processing of a method. This is achieved by the creation of a
derived exception class containing a collection of other exceptions
(a slightly modified version follows):</p>
<pre class="programlisting">
class FooException extends Exception {
  private ArrayList exceptions;
  public FooException(ArrayList exs) {
    exceptions = exs;
  }
  public ArrayList getExceptions() {
    return exceptions;
  }
}
</pre>
<p>And the original code is modified to make use of this
exception:</p>
<pre class="programlisting">
public static ArrayList foo(Connection conn)
           throws FooException {
  ArrayList exceptions = new ArrayList(); 
  ArrayList results = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {   
    // create a query, perform the query and
    // process the results
  }
  catch(SQLException ex) {
    exceptions.add(exception);
  }
  finally {
    try {
      rs.close();
    }
    catch(SQLException ex) {
      exceptions.add(ex);
    }
    try {
      ps.close();
    }
    catch(SQLException ex) {
      exceptions.add(ex);
    }
    if(exceptions.size() != 0) {
      throw new FooException(exceptions);
    }
  }
  return results;
}
</pre>
<p>This approach doesn't lose any of the exceptions thrown and the
<tt class="classname">PreparedStatement</tt> will be closed even if
the <tt class="methodname">close</tt> of the <tt class=
"classname">ResultSet</tt> throws an exception, but now the method
throws a user-defined <tt class="exceptionname">Exception</tt>
instead of <tt class="exceptionname">SQLException</tt>. It is
better to use standard exceptions where possible as discussed in
[<a href="#Bloch">Bloch</a>] &quot;Item 42: Favor the use of standard
exceptions&quot;. More importantly the exceptions are collected as peers
not as causes, and so is not idiomatic (at least not since JDK1.4)
where the <tt class="exceptionname">Throwable</tt> class allows
nesting of another <tt class="exceptionname">Throwable</tt> as a
cause [ <a href="#JDK14">JDK14</a>].</p>
<p><tt class="exceptionname">SQLException</tt> was written before
JDK1.4 and has its own mechanism for nesting other <tt class=
"exceptionname">SQLException</tt>s, this is supported by methods
<tt class="methodname">setNextException()</tt> and <tt class=
"methodname">getNextException()</tt>. This mechanism, being limited
to <tt class="exceptionname">SQLException</tt>, is not generally
idiomatic for all <tt class="exceptionname">Throwable</tt> types
and so will be not be considered for the purposes of this
article.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e257" id="d0e257"></a>A More
Idiomatic Approach?</h2>
</div>
<p>So a <tt class="exceptionname">Throwable</tt> (and its derived
classes) can be constructed with a cause (if this support has been
implemented), or can be initialized with a cause using the
<tt class="methodname">initCause()</tt> method. Nesting exceptions
at different levels of abstraction has been idiomatic even before
support was added to <tt class="exceptionname">Throwable</tt>, an
implementation of this can be found at <a href=
"http://www.javaworld.com/javaworld/javatips/jw-javatip91.html"
target=
"_top">http://www.javaworld.com/javaworld/javatips/jw-javatip91.html</a>.
So to be more idiomatic the same approach should be taken within
the original method.</p>
<p>We can use a modified version of Hagger's solution, combining
this with nested <tt class="literal">try</tt>/<tt class=
"literal">finally</tt> blocks from the first solution and nest the
<tt class="exceptionname">SQLException</tt>s using <tt class=
"methodname">initCause()</tt>, if required. Thus the original code
is rewritten:</p>
<pre class="programlisting">
public static ArrayList foo(Connection conn)
          throws SQLException {
  SQLException cachedException = null;
  ArrayList results = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  // assign query to ps
  try {
    // perform query and assign result to rs
    try {
      // process the results 
    }
    catch(SQLException ex) {
      cachedException = ex;
      throw ex;
    }
    finally {
      try {
        rs.close();
      }
      catch(SQLException ex) {
        if(cachedException != null) {
          ex.initCause(cachedException);
        }
        cachedException = ex;
        throw ex;
      }
    }
  }
  catch(SQLException ex) {
    if(cachedException != null) {
      ex.initCause(cachedException);
    }
    cachedException = ex;
    throw ex;
  }
  finally {
    try {
      ps.close();
    }
    catch(SQLException ex) {
      if(cachedException != null) {
        ex.initCause(cachedException);
      }
      throw ex;
    }
  }
  return results;
}
</pre>
<p>This solves the three problems of the original code, no
exception is lost, the exception thrown is a <tt class=
"exceptionname">SQLException</tt> and the <tt class=
"classname">PreparedStatement</tt> is closed even if the attempt to
close the <tt class="classname">ResultSet</tt> results in an
<tt class="exceptionname">Exception</tt>. Unfortunately this isn't
a general solution, the <tt class="methodname">initCause()</tt>
method is used to set the cause of a <tt class=
"exceptionname">SQLException</tt> if an existing <tt class=
"exceptionname">SQLException</tt> had been caught, but <tt class=
"methodname">initCause()</tt> has some restrictions:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;public Throwable initCause(Throwable cause) Initializes the
cause of this throwable to the specified value. (The cause is the
throwable that caused this throwable to get thrown.) This method
can be called at most once. It is generally called from within the
constructor, or immediately after creating the throwable. If this
throwable was created with Throwable(Throwable) or
Throwable(String,Throwable), this method cannot be called even
once.&quot; [<a href="#JDK14">JDK14</a>]</p>
</blockquote>
</div>
<p>This means that if the exceptions caught in the <tt class=
"literal">finally</tt> block already have a cause then the
<tt class="methodname">initCause()</tt> method call will fail with
a <tt class="exceptionname">java.lang.IllegalStateException</tt>.
To explain further this example demonstrates how to provoke the
failure:</p>
<pre class="programlisting">
void AnotherThrowingMethod() {
  throw new RuntimeException();
}
void ThrowingMethod() {
  try {
    AnotherThrowingMethod();
  }
  catch(RuntimeException ex) {
    throw new RuntimeException(ex);
  }
}
void foo() throws Exception {
  Exception cachedException = null;
  try {
    ThrowingMethod();
  }
  catch(Exception ex) {
    cachedException = ex;
    throw ex;
  }
  finally {
    try {
      ThrowingMethod();
    }
    catch(Exception ex) {
      if(cachedException != null) {
        ex.initCause(cachedException);
        // error: IllegalStateException 
        // Exception ex already has a cause
      }
      throw ex;
    }
  }
}
</pre>
<p>The idiomatic approach could be written to check for this
situation, for example the handling of the <tt class=
"classname">PreparedStatement</tt> could become:</p>
<pre class="programlisting">
if(ps != null) {
  try {
    ps.close();
  }
  catch(SQLException ex) {
    if(ex.getCause() == null) {
      if(cachedException != null) {
        ex.initCause(cachedException);
      }
    }
    throw ex;
  }
}
</pre>
<p>But this will mean that the original exception is lost, as
discussed above, making Hagger's approach better in this case.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e344" id="d0e344"></a>Summary</h2>
</div>
<p>Handling exceptions thrown while in a <tt class=
"literal">finally</tt> block is problematic in the context of an
existing exception. This article has presented some approaches that
solve at least some of the problems discovered in the example but
no approach is entirely satisfactory. For the example presented the
idiomatic solution works and is the best solution.</p>
<p>In the wider context of a general solution each approach has
drawbacks or will not work, for example the idiomatic approach will
fail if the exception being handled already has a cause. Of the
approaches presented I would use, in order of preference, the
idiomatic version, then Hagger's approach (if the exceptions being
handled could already have a cause). I would resist using the
approach in [<a href="#Warren-">Warren-</a>] as ignoring exceptions
is a particularly bad idiom and should be avoided under any
circumstances.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e357" id=
"d0e357"></a>Bibliography</h2>
</div>
<div class="bibliomixed"><a name="Bloch" id="Bloch"></a>
<p class="bibliomixed">[Bloch] Joshua Bloch, <span class=
"citetitle"><i class="citetitle">Effective Java - Programming
Language Guide</i></span>, Addison-Wesley 0-201-31005-8</p>
</div>
<div class="bibliomixed"><a name="Eckel" id="Eckel"></a>
<p class="bibliomixed">[Eckel] Bruce Eckel, <span class=
"citetitle"><i class="citetitle">Thinking in Java</i></span>, 3rd
Edition, Prentice-Hall 0-131-002872</p>
</div>
<div class="bibliomixed"><a name="Griffiths" id="Griffiths"></a>
<p class="bibliomixed">[Griffiths] Alan Griffiths, &quot;More
Exceptional Java,&quot; <span class="citetitle"><i class=
"citetitle">Overload 49</i></span> and also available at
<span class="bibliomisc"><a href=
"http://www.octopull.demon.co.uk/java/MoreExceptionalJava.html"
target=
"_top">http://www.octopull.demon.co.uk/java/MoreExceptionalJava.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Hagger" id="Hagger"></a>
<p class="bibliomixed">[Hagger] Peter Hagger, <span class=
"citetitle"><i class="citetitle">Practical Java - Programming
Language Guide</i></span>, Addison-Wesley 0-201-61646-7</p>
</div>
<div class="bibliomixed"><a name="JDK14" id="JDK14"></a>
<p class="bibliomixed">[JDK14] <span class="bibliomisc"><a href=
"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html"
target=
"_top">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html</a></span></p>
</div>
<div class="bibliomixed"><a name="Warren-" id="Warren-"></a>
<p class="bibliomixed">[Warren-] Nigel Warren and Philip Bishop,
<span class="citetitle"><i class="citetitle">Java in Practice -
Design Styles and Idioms for Effective Java</i></span>,
Addison-Wesley 0-201- 36065-9</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
