    <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  :: Exception Handling in C#</title>
        <link>https://members.accu.org/index.php/journals/378</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 #51 - Oct 2002 + 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/c194/">51</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/c194-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c194+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;Exception Handling in C#</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 October 2002 22:58:12 +01:00 or Wed, 02 October 2002 22:58:12 +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>In the absence of exceptions the classic way to handle errors is
to intertwine your statements with error checks. For example:</p>
<pre class="programlisting">
  public sealed class Painful {
      ...
      private static char[] ReadSource(string filename) {
          FileInfo file = new FileInfo(filename);
          if (errorCode == 2342) goto handler;
          int length = (int)file.Length;
          char[] source = new char[length];
          if (errorCode == -734) goto handler;
          TextReader reader = file.OpenText();
          if (errorCode == 2664) goto handler;
          reader.Read(source, 0, length);
          if (errorCode == -5227) goto handler;
          reader.Close();
          Process(filename, source);
          return source;
          handler:
          ...
      }
  }
</pre>
<p>This style of programming is tedious, repetitive, awkward,
complex, and obscures the essential functionality. And it's too
easy to ignore errors (either deliberately or accidentally). There
have to be better ways. And there are. But some are better than
others.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e26" id="d0e26"></a>Separation of
Concerns</h2>
</div>
<p>The fundamental thing that exceptions allow you to do is to
<span class="emphasis"><em>separate</em></span> the essential
functionality from the error handling. In other words, we can
rewrite the mess above like this:</p>
<pre class="programlisting">
  ...
  public sealed class PainLess {

      public static int Main(string[] args) {
          try {
              string filename = args[0];
              char[] source = ReadSource(filename);
              Process(filename, source);
              return 0;
          }
          catch (SecurityException caught) {...}
          catch (IOException caught) {...}
          catch (OutOfMemoryException caught) {...}
          ...
      }

      private static char[] ReadSource(string filename) {
          FileInfo file = new FileInfo(filename);
          int length = (int)file.Length;
          char[] source = new char[length];
          TextReader reader = file.OpenText();
          reader.Read(source, 0, length);
          reader.Close();
          return source;
      }
  }
</pre>
<p>There are several things to notice about this
transformation.</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>The numeric integer error codes that utterly failed to describe
the errors they represented (e.g. what does 2342 mean?) are now
descriptive exception classes (e.g. <tt class=
"literal">SecurityException</tt>).</p>
</li>
<li>
<p>The exception classes are not tightly coupled to each other. In
contrast, each integer code must hold a unique value thus coupling
all the error codes together.</p>
</li>
<li>
<p>There is no throw specification on <tt class=
"literal">ReadSource</tt>. C# does not have <tt class=
"literal">throw</tt> specifications.</p>
</li>
</ul>
</div>
<p>However, by far and away the most important thing is how clean,
simple and easy to understand <tt class="literal">ReadSource</tt>
is. It contains the statements required to implement its essential
functionality and nothing else. There is no apparent concession to
error handling. This is possible because if an exception occurs the
call stack will unwind all by itself. This version of <tt class=
"literal">ReadSource</tt> is the &quot;ideal&quot; we are aiming it. It is as
direct as we can make it.</p>
<p>Ironically, exceptions allow us to get close to this ideal
version of <tt class="literal">ReadSource</tt> but at the same time
prevent us from quite reaching it. The problem is that <tt class=
"literal">ReadSource</tt> is an example of code that acquires a
resource (a <tt class="literal">TextReader</tt>), uses the resource
(<tt class="literal">Read</tt>), and then releases the resource
(<tt class="literal">Close</tt>). The problem is that if an
exception occurs after acquiring the resource but before releasing
it then the release will not take place. The solution has become
part of the context. Nevertheless, this &quot;ideal&quot; version of
<tt class="literal">ReadSource</tt> is useful; we can compare
forthcoming versions of <tt class="literal">ReadSource</tt> to it
as a crude estimate of their &quot;idealness&quot;.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e88" id="d0e88"></a>finally?</h2>
</div>
<p>The solution to this lost release problem depends on the
language you're using. In C++ you can release the resource in the
destructor of an object held on the stack (the misnamed Resource
Acquisition Is Initialization idiom). In Java you can use a finally
block. C# allows you to create user-defined struct types that live
on the stack but does not allow struct destructors. (This is
because a C# destructor is really a <tt class=
"literal">Finalize</tt> method in disguise and Finalize is called
by the garbage collector. Structs, being value types, are never
subject to garbage collection.) Therefore, initially at least, C#
must follow the Java route and use a finally block. A first cut
implementation using a finally block might look like this:</p>
<pre class="programlisting">
  private static char[] ReadSource(string filename) {
      try {
          FileInfo file = new FileInfo(filename);
          int length = (int)file.Length;
          char[] source = new char[length];
          TextReader reader = file.OpenText();
          reader.Read(source, 0, length);
      }
      finally {
          reader.Close();
      }
      return source;
  }
</pre>
<p>This version has had to introduce a try block (since a finally
block must follow a try block) which isn't in the ideal solution
but apart from that it's the same as the &quot;ideal&quot; version of
<tt class="literal">ReadSource</tt>. It would be a reasonable
solution if it worked. But it doesn't. The problem is that the try
block forms a scope so reader is not in scope inside the finally
block and source is not in scope at the return statement.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e103" id="d0e103"></a>finally?</h2>
</div>
<p>To solve this problem you have to move the declarations of
reader and source outside the try block. A second attempt might
be:</p>
<pre class="programlisting">
  private static char[] ReadSource(string filename) {
      TextReader reader;
      char[] source;
      try {
          FileInfo file = new FileInfo(filename);
          int length = (int)file.Length;
          source = new char[length];
          reader = file.OpenText();
          reader.Read(source, 0, length);
      }
      finally {
          reader.Close();
      }
      return source;
  }
</pre>
<p>This version has moved the declaration of reader and source out
of the try block and consequently, inside the try block, assigns to
reader and source rather than <span class=
"emphasis"><em>initializing</em></span> them. That's another
difference (and two extra lines) from the &quot;ideal&quot; version of
<tt class="literal">ReadSource</tt>. Nevertheless, you might
consider it a reasonable solution if it worked. But it doesn't. The
problem is that assignment is not the same as initialization and
the compiler knows it. If an exception is thrown before reader is
assigned then the call to <tt class="literal">reader.Close()</tt>
in the finally block will be on reader which won't be assigned. C#,
like Java, doesn't allow that.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e121" id="d0e121"></a>finally?</h2>
</div>
<p>Clearly you have to initialize <tt class="literal">reader</tt>.
A third attempt therefore might be:</p>
<pre class="programlisting">
  private static char[] ReadSource(string filename) {
      TextReader reader = null;
      char[] source;
      try {
          FileInfo file = new FileInfo(filename);
          int length = (int)file.Length;
          source = new char[length];
          reader = file.OpenText();
          reader.Read(source, 0, length);
      }
      finally {
          reader.Close();
      }
      return source;
  }
</pre>
<p>This version introduces null which isn't in the &quot;ideal&quot; version
of <tt class="literal">ReadSource</tt>. Nevertheless, you might
still consider it a reasonable solution if it worked. But it
doesn't (although it does compile). The problem is the call to
<tt class="literal">reader.Close()</tt> could easily throw a
<tt class="literal">NullReferenceException</tt>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e142" id="d0e142"></a>finally?</h2>
</div>
<p>One way to solve this problem is to guard the call to <tt class=
"literal">reader.Close()</tt>. A fourth attempt therefore might
be:</p>
<pre class="programlisting">
  private static char[] ReadSource(string filename) {
      TextReader reader = null;
      char[] source;
      try {
          FileInfo file = new FileInfo(filename);
          int length = (int)file.Length;
          source = new char[length];
          reader = file.OpenText();
          reader.Read(source, 0, length);
      }
      finally {
          if (reader != null)
              reader.Close();
      }
      return source;
  }
</pre>
<p>Of course, the guard on <tt class="literal">reader.Close()</tt>
isn't in the &quot;ideal&quot; version of <tt class=
"literal">ReadSource</tt>. But this is a reasonable version if only
because it does, finally, work. It's quite different from the
&quot;ideal&quot; version but with a bit of effort you can refactor it to
this:</p>
<pre class="programlisting">
  private static char[] ReadSource(string filename) {
      FileInfo file = new FileInfo(filename);
      int length = (int)file.Length;
      char[] source = new char[length];
      TextReader reader = file.OpenText();
      try {
          reader.Read(source, 0, length);
      }
      finally {
          if (reader != null)
              reader.Close();
      }
      return source;
  }
</pre>
<p>In some cases you might be able to drop the null guard inside
the finally block but in general this is the best you can do with a
finally block solution. (Consider if <tt class=
"literal">file.OpenText</tt> returned <tt class=
"literal">null</tt>.) You have to add a try block, a finally block,
and an if guard. And if you are using Java you have to do those
three things every time. And therein is the biggest problem. If
this solution was truly horrible and completely and utterly
different to the ideal solution it wouldn't matter a jot if we
could abstract it all away. But in Java you can't. The Java road
stops here, but the C# road continues.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e170" id="d0e170"></a>using
Statements</h2>
</div>
<p>In C#, the nearest you can get to the &quot;ideal&quot; version is
this:</p>
<pre class="programlisting">
  private static char[] ReadSource(string filename) {
      FileInfo file = new FileInfo(filename);
      int length = (int)file.Length;
      char[] source = new char[length];
      using (TextReader reader = file.OpenText()){ reader.Read(source, 0, length); }
      return source;
  }
</pre>
<p>This is pretty close. And as I'll explain shortly it has a
number of features that <span class=
"emphasis"><em>improve</em></span> on the &quot;ideal&quot; version. But
first let's look under the lid to see how it actually works.</p>
<p>The C# ECMA specification states that a using statement:</p>
<pre class="programlisting">
  using (type variable = initialization)
      embeddedStatement
</pre>
<p>is equivalent to:</p>
<pre class="programlisting">
  {
      type variable = initialization;
      try { embeddedStatement }
      finally {
          if (variable != null) {
              ((IDisposable)variable).Dispose();
          }
      }
  }
</pre>
<p>This relies on the <tt class="literal">IDisposable</tt>
interface from the <tt class="literal">System</tt> namespace:</p>
<pre class="programlisting">
  namespace System {
      public interface IDisposable {
          void Dispose();
      }
  }
</pre>
<p>Note that the cast inside the finally block implies that
variable must be of a type that supports the <tt class=
"literal">IDisposable</tt> interface (either via inheritance or
conversion operator). If it doesn't you'll get a compile time
error.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e205" id="d0e205"></a>using
TextReader Translation</h2>
</div>
<p>Not surprisingly, <tt class="literal">TextReader</tt> supports
the <tt class="literal">Disposable</tt> interface and implements
<tt class="literal">Dispose</tt> to call <tt class=
"literal">Close</tt>. This means that this:</p>
<pre class="programlisting">
  using (TextReader reader = file.OpenText()) {
      reader.Read(source, 0, length);
  }
</pre>
<p>is translated, under the hood, into this:</p>
<pre class="programlisting">
  { TextReader reader = file.OpenText();
      try { reader.Read(source, 0, length); }
      finally {
          if (reader != null) {
              ((IDisposable)reader).Dispose();
          }
      }
  }
</pre>
<p>Apart from the cast to <tt class="literal">IDisposable</tt> this
is identical to the best general Java solution. The cast is
required because this is a general solution.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e233" id="d0e233"></a>Do It
Yourself?</h2>
</div>
<p>It's instructive to consider what would happen if <tt class=
"literal">TextReader</tt> didn't implement the <tt class=
"literal">Disposable</tt> interface. The lessons from this will
show us how to implement Disposability in our own classes. One
solution is the Object Adapter pattern. For example:</p>
<pre class="programlisting">
  public sealed class AutoTextReader: Idisposable {
      public AutoTextReader(TextReader target) {
          // PreCondition(target != null);
          adaptee = target;
      }

      // readonly property
      public TextReader TextReader {
          get { return adaptee; }
      }

      public void Dispose() {
          adaptee.Close();
      }

      private readonly TextReader adaptee;
  }
</pre>
<p>which you would use like this:</p>
<pre class="programlisting">
  using (AutoTextReader scoped = new AutoTextReader(file.OpenText())) {
      scoped.TextReader.Read(source, 0, length);
  }
</pre>
<p>To make things a little easier you can create an implicit
conversion operator:</p>
<pre class="programlisting">
  public sealed class AutoTextReader: Idisposable {
      ...
      public static implicit operator AutoTextReader(TextReader target) {
          return new AutoTextReader(target);
      }
      ...
  }
</pre>
<p>which would allow you to write this:</p>
<pre class="programlisting">
  using (AutoTextReader scoped = file.OpenText()) {
      scoped.TextReader.Read(source, 0, length);
  }
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e258" id="d0e258"></a>struct
Alternative</h2>
</div>
<p><tt class="literal">AutoTextReader</tt> is a sealed class
intended, as its name suggests, to be used as a local variable. It
makes sense to implement it as a struct instead of class:</p>
<pre class="programlisting">
  public struct AutoTextReader : Idisposable {
      // exactly as before
  }
</pre>
<p>Using a struct instead of a class also gives you a couple of
free optimizations. Since a struct is a value type it can never be
null. This means the compiler can omit the null guard from
generated finally block. Also, since you cannot derive from a
struct its runtime type is always the same as its compile time
type. This means the compiler can also omit the cast to <tt class=
"literal">IDisposable</tt> from the generated finally block and
thus avoid a boxing operation. In other words, when <tt class=
"literal">AutoTextReader</tt> is a struct, this:</p>
<pre class="programlisting">
  using (AutoTextReader scoped = file.OpenText()) {
      scoped.TextReader.Read(source, 0, length);
  }
</pre>
<p>is translated into this:</p>
<pre class="programlisting">
  {
      AutoTextReader scoped = new file.OpenText();
      try {
          scoped.TextReader.Read(source, 0, length);
      }
      finally {
          scoped.Dispose();
      }
  }
</pre>
<p>It should come as no surprise that I prefer the using statement
solution to the finally block solution. In fact, the using
statement solution scores several extra points in comparison to the
&quot;ideal&quot; solution. A using statement</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Works! It always releases the resource.</p>
</li>
<li>
<p>Is an extensible mechanism. It allows you to create an
abstraction of resource release. Creating your own resource
releaser types such as <tt class="literal">AutoTextReader</tt> is
easy.</p>
</li>
<li>
<p>Allows you to pair up the resource acquisition with the resource
release. The best moment to organize the resource release is the
moment you acquire the resource. If you borrow a book from a
library you're told when to return it as you borrow it.</p>
</li>
<li>
<p>Creates a scope for the variable holding the resource. Look
carefully at the compiler translation of a using statement and
you'll see that it cleverly includes a pair of outer braces:</p>
<pre class="programlisting">
  using (AutoTextReader scoped = file.OpenText()) {
      scoped.TextReader.Read(source, 0, length);
  }
  scoped.TextReader.Close(); // scoped is not
                             // in scope here
</pre></li>
</ul>
</div>
<p>This is reminiscent of C++ declarations in conditions. Both
allow you to restrict the scope of a variable so it's only usable
when in scope and is only in scope when usable. This is more than
just a syntactic nicety since any attempt to use a released
resource could well throw an exception.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
