CaubleStone Ink

.Net development and other geeky stuff

Exception Handling Basics

Posted on April 14th, 2009


Download the code Here.

It’s amazing to see how exception handling is not used properly after all these years that the .net framework has been out. Some of it can be attributed to the Internet since anybody can post information anywhere, it get’s propagated through google and then upcoming developers find it and think that is how things are done. Of course for those that understand exception handling it’s always obvious when you see a rookie mistake. I don’t think we should always blame the rookie since still to this day people post things with bad exception handling just making the problem worse.

The goal of this is to show you a very very simple sample to show how you should code your exception handling so that if you ever have to debug a problem you can get right to it instead of having to find it.

I’m going to give you three examples of exception handling. Two of them work correctly. The first one I will show is what you tend to find a lot. This is the one that is wrong. I cannot say that rookies are the only ones that do this either. There are plenty of people that are very strong that still make this simple mistake. However it can mean a world of difference when done right and you run into a production problem.

The wrong way:

public void ExceptionHandlingA()
{
    try
    {
	throw new ArgumentNullException("ExceptionA", "Test Exception Call from DoStuff.ExceptionHandlingA");
    }
    catch (Exception ex)
    {
	throw ex;
    }
}

Now you may ask or even tell yourself that there is nothing wrong with this statement. The problem is both subtle and devious. It all hinges on your Catch block. Just looking at this statement you think it bubbles the exception up. While it does bubble it up what is wrong with this is that it bubbles it up as a new exception object. While if you only have a single layer of code this would never be obvious. However if you are calling this method from other classes that then are called by other classes is where you start to run into your problem.

Next I’ll show you two proper methods that do exception handling and then walk you through creating the code you need to show the very subtle difference in the result. Namely the stacktrace.

Good Exceptions:

public void ExceptionHandlingB()
{
    try
    {
	throw new ArgumentNullException("ExceptionB", "Test Exception Call from DoStuff.ExceptionHandlingB");
    }
    catch (Exception ex)
    {
	throw;
    }
}


public void ExceptionHandlingC()
{
    try
    {
	throw new ArgumentNullException("ExceptionC", "Test Exception Call from DoStuff.ExceptionHandlingC");
    }
    catch
    {
	throw;
    }
}

Now if you look at this code you will see that the only thing that is different is that in the Catch block we only use the keyword throw. This is very important and something you should understand. Basically when you call just the word throw it does a re-throw in the IL for .net whereas the other throw ex command creates a new exception.

In case you don’t believe what I’ve just said here is the IL from the Bad exception handler:

.method public hidebysig instance void  ExceptionHandlingA() cil managed
{
  // Code size       22 (0x16)
  .maxstack  3
  .locals init ([0] class [mscorlib]System.Exception ex)
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  ldstr      "ExceptionA"
    IL_0007:  ldstr      "Test Exception Call from DoStuff.ExceptionHandlingA"
    IL_000c:  newobj     instance void [mscorlib]System.ArgumentNullException::.ctor(string,
                                                                                     string)
    IL_0011:  throw
  }  // end .try
  catch [mscorlib]System.Exception
  {
    IL_0012:  stloc.0
    IL_0013:  nop
    IL_0014:  ldloc.0
    IL_0015:  throw
  }  // end handler
} // end of method DoStuff::ExceptionHandlingA

and the code from the good exception handler:

.method public hidebysig instance void  ExceptionHandlingC() cil managed
{
  // Code size       22 (0x16)
  .maxstack  3
  IL_0000:  nop
  .try
  {
    IL_0001:  nop
    IL_0002:  ldstr      "ExceptionC"
    IL_0007:  ldstr      "Test Exception Call from DoStuff.ExceptionHandlingC"
    IL_000c:  newobj     instance void [mscorlib]System.ArgumentNullException::.ctor(string,
                                                                                     string)
    IL_0011:  throw
  }  // end .try
  catch [mscorlib]System.Object
  {
    IL_0012:  pop
    IL_0013:  nop
    IL_0014:  rethrow
  }  // end handler
} // end of method DoStuff::ExceptionHandlingC

If you notice towards the end of the IL that on the good one it uses the command rethrow where the bad handler does not. This is very important as the rethrow command allows your exception objects to retain the full stacktrace. Since stacktraces are very important in helping you find where your problem is the better it is the faster you can find your problem and fix it.

Now to show you what we have done so you can see for your own eyes. Create a new VS Console project or just put this stuff in notepad and compile using the SDK. Whatever your preference. I’ve included a VS2008 version of the project for download if you just want to download and run it.

Take the first three methods from a above and put them in a class called DoStuff like so:

using System;
using System.Collections.Generic;
using System.Text;

namespace EffectiveErrorHandling
{
    class DoStuff
    {
        public void ExceptionHandlingA()
        {
            try
            {
                throw new ArgumentNullException("ExceptionA", "Test Exception Call from DoStuff.ExceptionHandlingA");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void ExceptionHandlingB()
        {
            try
            {
                throw new ArgumentNullException("ExceptionB", "Test Exception Call from DoStuff.ExceptionHandlingB");
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public void ExceptionHandlingC()
        {
            try
            {
                throw new ArgumentNullException("ExceptionC", "Test Exception Call from DoStuff.ExceptionHandlingC");
            }
            catch
            {
                throw;
            }
        }

    }
}

Next we are going to create a second layer that calls this class using the same exception handling constructs for each method type so we create a layer that can absorb our exceptions to show the loss of the stacktrace.


using System;
using System.Collections.Generic;
using System.Text;

namespace EffectiveErrorHandling
{
    class CallStuff
    {
        public void CallExceptionA()
        {
            try
            {
                DoStuff d = new DoStuff();
                d.ExceptionHandlingA();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void CallExceptionB()
        {
            try
            {
                DoStuff d = new DoStuff();
                d.ExceptionHandlingB();
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public void CallExceptionC()
        {
            try
            {
                DoStuff d = new DoStuff();
                d.ExceptionHandlingC();
            }
            catch
            {
                throw;
            }
        }

    }
}

Next put the following code in your Program.cs file:

using System;
using System.Collections.Generic;
using System.Text;

namespace EffectiveErrorHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            CallStuff c = new CallStuff();

            Console.WriteLine("Calling Exception Type A");
            try
            {
                c.CallExceptionA();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("Calling Exception Type B");
            try
            {
                c.CallExceptionB();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("Calling Exception Type C");
            try
            {
                c.CallExceptionC();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
    }
}

As you can see here we are handling the exception that is raised in each case and outputing it to the console.

Download the code Here.

Now if you are trusting this is the output from the program when you run it. As you can see the first exception has one less level of detail due to the fact that it does not rethrow the exception but instead it creates a new copy of the exception for bubbling up. So as you are progressing through your development career please take this to heart. You’ll thank me for it when you run up against some bug which you could have found and fixed if you had the right exception handling in place.

Output from the console:


Calling Exception Type A
Test Exception Call from DoStuff.ExceptionHandlingA
Parameter name: ExceptionA
at EffectiveErrorHandling.CallStuff.CallExceptionA() in G:\a951072\My Documen
ts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Cal
lStuff.cs:line 18
at EffectiveErrorHandling.Program.Main(String[] args) in G:\a951072\My Docume
nts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Pr
ogram.cs:line 16

Calling Exception Type B
Test Exception Call from DoStuff.ExceptionHandlingB
Parameter name: ExceptionB
at EffectiveErrorHandling.DoStuff.ExceptionHandlingB() in G:\a951072\My Docum
ents\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\D
oStuff.cs:line 29
at EffectiveErrorHandling.CallStuff.CallExceptionB() in G:\a951072\My Documen
ts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Cal
lStuff.cs:line 31
at EffectiveErrorHandling.Program.Main(String[] args) in G:\a951072\My Docume
nts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Pr
ogram.cs:line 27

Calling Exception Type C
Test Exception Call from DoStuff.ExceptionHandlingC
Parameter name: ExceptionC
at EffectiveErrorHandling.DoStuff.ExceptionHandlingC() in G:\a951072\My Docum
ents\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\D
oStuff.cs:line 42
at EffectiveErrorHandling.CallStuff.CallExceptionC() in G:\a951072\My Documen
ts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Cal
lStuff.cs:line 45
at EffectiveErrorHandling.Program.Main(String[] args) in G:\a951072\My Docume
nts\Visual Studio 2008\Projects\EffectiveErrorHandling\EffectiveErrorHandling\Pr
ogram.cs:line 38

Building your code or CI and you

Posted on January 27th, 2009


I’ve been seeing alot of stuff on the web lately considering continuous integration (CI), automated builds, build tools, unit testing, etc.  Figured maybe it’s time I start to post about some of this stuff.  I’ve been using CI in various shapes and sizes as it were for many years.  From custom rolled solutions to full commercial packages.  As such I will be posting many articles around CI, builds, unit testing, etc to help people who maybe have never seen it before or even if I’m lucky have an answer to a problem you have been having.

First let me say that I don’t care if you are a single person shop, team, department, or whole company.  You NEED to be using some form of CI.  There are free versions out there like Cruise Control.net and TeamCity (which is now free for limited installations).  I personnally have setup a TeamCity installation on my big developer desktop and I’m just a one person show for the stuff I do at home.

So, what is CI and why should you use it. CI is a means by which you can have an autonomous process running somewhere either on your machine, server, cloud computing platform, server farm, you name it that will take your code and compile it.  Big whoop-dee-do you say I can do that by just building from my desktop in my IDE.  Ok, that’s great if you are a one person shop.  But what happens if you don’t get the latest from your source control and yeah it builds with the code you have but your buddy in the cube across from you just changed everything.  Now your build won’t work but you don’t find out till later when somebody says something.  This is where CI comes into play.  It does not remove the build check from your box.  You should always do that.  Where CI comes in is a sanity check and a means to automate tedious tasks.  Using the scenario above what happens when two people check in code at the same time such that you both think everything is working but then in the morning you get latest and bam nothing compiles.  Wouldn’t it have been nice to have something email you telling you that it broke and maybe even why.  What about unit tests.  Do you use them, run them, all the time, some of the time, etc.  You could have all this automated for you upfront.

Now setting up a CI system is an upfront task, yes it takes some time, yes there could be integration issues with your code base, yes you may need to change the way you build code.  But in the end it’s all worth it.  Once you get onto a CI system and everything is up and running you will start to get a sense of peace.  Not only that but you will quickly come to rely upon it.  It becomes that great little tool that you wish you had found sooner.

Now the catch.  If you don’t use a Source Control provider at the minimum CI wont’ do much for you.  You really should be using source control.  This comes back into the you MUST do this category.  Again I don’t care if you are just one person or a whole company.  You NEED source control.

Why is this important if you are a single person.  Well what happens when you inadvertantly delete a folder with code and you had no backup.  Come on how many tech people do you know who actively backup there stuff?  If it’s not automated we don’t usually do it.  Let’s even say that you are working on some project that you might want to sell.  How do you know if you have everything.  Just because your folder is there doesn’t count.  What happens if you need to have somebody help you code the app, so you just went from being a one person show to a small team.  If you have source control your golden.  Just give them access and away you go.  It is an important process and does not need to be strictly used for source code.  I’ve used it for word docs so I can go back and pull say a version 1 of a requirement spec to show the business unit / partner how things have changed over the course of say a year or even a month.  You just never know.

CI needs source control.  It provides a means by which you can have a 3rd party verify your code base.  In a single person shop it can tell you if you have really checked in all your code.  So let’s say you the one man team are working on two or more computers.  If you have source control it’s easy to share all your code across the wire and know that you have everything because your CI build is working based on what is in the repository.

Another good use of CI is that in most tools you can even setup scheduled builds, say like a nightly build.  What if you have a project where you want to provide a nightly build to people.  You could setup your build script to actually take all your code build it and zip it.  The CI server can do this for you.  So no late nights, waiting for people to finish.  You can then even have the CI server send you emails when it succeeds or fails.

The advantages to running CI and source control are to many to number.  If you haven’t ever used them I suggest you do so.  Go get Subversion and TeamCity at the minimum and install them.  Work through them, play with them, and use them.  They will save you time, money, and effort in the end.

In the next posts I hope to show you how to get a subversion installation up and running on Windows along with configuring TeamCity to use the same setup.  I’ll even start posting some topics on using nAnt and unit testing.

The more we can test and automate our build and deployments the more time we can spend actually coding our solutions.

Application Helpers: Protect your method calls

Posted on January 26th, 2009


First thing, refactor, refactor, refactor. Most ideas come from refactoring of your code. It’s amazing how much you do when you start refactoring things. The big benefit of course is less code. If you have a couple hundred thousand lines of code or even ten thousand lines of code, refactoring even a small thing can cut down your code base and improve readability. This article is geared towards refactoring.

In the course of working on multiple applications over the years you find you tend to do the same things over and over again. One of those things is constantly checking objects for null, data type compatibility, etc. How many times have you written the following lines of code.

if (object == null)
{
   throw new ArgumentNullException();
}

or

if (object.GetType() == typeof(sometype))

The amount of code there justs adds up. Not only that but you probably have lots of null checks maybe even in the same method. So what if we wrote something like this instead:

Protect.IsNotNull(obj, "The object you are checking is null");

So if you had multiple objects going into an object you would have something like this:

Protect.IsNotNull(obj1, "Object 1 is null");
Protect.IsNotNull(obj2, "Object 2 is null");

Now since we are talking about refactoring what if we even refactor that code to make use of the newer features of the framework. Since the Protect methods throw an exception if the object is null in this case what if we wanted to expand it to allow for multiple checks. We could do something like this:

Protect.Against(obj1 == null, "Object 1 is null");
Protect.Against(String.IsNullOrEmpty(stringData), "The string is emtpy.");

As you can see we can now handle multiple things at the same time. So let’s look at what is under the Protect method.

public static class Protect
{
  public static void Against(bool condition, string message) where T: Exception
  {
    if (condition)
      throw new (T)Activator.CreateInstance(typeof(T), message);
  }
}

As you can see not much but it makes your code easier to read and it adds a nice bit of conformity while reducing the total lines you need to maintain and worry about. The T parameter is the type of exception you want thrown based on your condition. As long as you have a boolean condition your good. Anything that evaluates to true will throw the exception. The message will be on the exception that is thrown. Based on this pattern we can also add things like Inheritance checks, Type checks, Enum, checks, etc. It’s really easy for it to morph into what you need as you need it. You can even extend it with delegates, Func<> methods, setup for linq style syntax, etc. the sky is the limit.

Here is what it would look like in use inside of a method:

public void DoSomething(List data, Dictionary other)
{
    Protect.Against(data == null, "Data is null");
    Protect.Against(other==null, "Other is null");

    foreach (int i in data)
    {
        Console.WriteLine(other[i]);
     }
}

Introduction to the Circuit Breaker pattern

Posted on March 6th, 2008


Download the code (14kb)

I was reading the book Release It! about a month ago and ran across this pattern for creating code that has the ability to essentially shut itself off.  It just so happens that I had a use for this type of process and it helped me to create my final design.  What I was working on was a component that used a third party webservice for batch processing.  In this batch we would send over anywhere from 50-1500 web request one right after the other.  As such if we had any problems on the service end we could have thrown 1500 or even more error messages depending on how it was coded.  Of course we did not want that as it could potentially cause even worse problems by letting our app continue to try and process our data even if the service was down.  So instead of needlessly killing each of our apps I took a queue from the book and implemented the circuit breaker pattern. 

Now you might ask what is the circuit breaker pattern?  Well lets take a look at a real world scenario that everybody is familiar with.  Every home today has a main power box that is the central point at which power enters the home.  Now depending on how old the home is you could either have circuit breakers, fuses, or even worse a piece of metal jammed between the connections (I’d hope not).  Now fuses and circuit breakers all work the same way and for the same reason, to regulate the amount of load that is allowed over the electrical wire.  This is important because if there were no limit then it would cause an electrical short somewhere and possibly a fire.  It happened a lot before the fuse was created.  So, the use of a fuse or circuit breaker is meant to make sure we don’t put too much of a load on the circuit or wire.  Once a threshold is met then the circuit is tripped or the fuse is blown.  Thus stopping the flow of power.  Now if we look at our code base we want the same thing to occur.  So if I were to start sending records to the service in question and they start constantly failing as long as we have setup a threshold for error counts or failures we can then trip our circuit so to say and stop the flow of data to this service. 

Well you might ask how can we do this?  In our code bases is really not all that difficult to implement once you get the concept down.  So let’s look at some code to create a small example application.  Now you don’t have to create an interface but I wanted to really show what you need to do to add this functionality to your existing code.

public interface ICircuitBreaker
{
    void BreakCircuit();
    void ResetCircuit();
    bool CircuitBroken { get; set; }
    int Threshold { get; set; }
}

Next I’m going to embed an entire class with the interface implemented.  To show how this works I have created a class that writes to a file.  If there is a problem writing to the file for a specified number of tries then it will fail gracefully vs throwing an exception.

public class FileWriterWithCB : ICircuitBreaker
  {
    private bool _circuitBroken;
    private int _threshold;
    private string _fileName;
    private int _batchSize;

    public FileWriterWithCB()
    {
      this._circuitBroken = false;
      this._threshold = 5;
      this._fileName = "CBTest.txt";
      this._batchSize = 50;
    }

    public string FileName
    {
      get { return this._fileName; }
    }

    public int BatchSize
    {
      get { return this._batchSize; }
      set { this._batchSize = value; }
    }

    public void WriteToFile()
    {
      FileStream fs = new FileStream(this._fileName, FileMode.Open, FileAccess.ReadWrite);

      StreamWriter sw = new StreamWriter(fs);

      string data = "This is a test file write";

      sw.Write(data);

      sw.Flush();
      sw.Close();
      fs.Flush();
      fs.Close();

      sw = null;
      fs = null;
    }

    public void RunBatchWithCircuitBreaker()
    {
      int failureCount = 1;

      for (int x = 0; x &lt;= this._batchSize; x++)
      {
        if (failureCount &gt; this._threshold)
        {
          Console.WriteLine("Threshold reached breaking circuit.");
          this.BreakCircuit();
        }
        if (this.CircuitBroken)
        {
          Console.WriteLine("Circuit is Broken exiting code loop.");
          return;
        }

        try
        {
          // This should throw a FileNotFound Exception
          this.WriteToFile();
        }
        catch (Exception ex)
        {
          failureCount++;
          // Just write to the console to show that it is throwing the errors.
          Console.WriteLine(ex.Message);
        }

      }

    }

    #region ICircuitBreaker Members

    public void BreakCircuit()
    {
      Console.WriteLine("Circuit is being broken.");
      this._circuitBroken = true;
    }

    public void ResetCircuit()
    {
      Console.WriteLine("Circuit is being reset.");
      this._circuitBroken = false;
    }

    public bool CircuitBroken
    {
      get
      {
        return this._circuitBroken;
      }
      set
      {
        this._circuitBroken = value;
      }
    }

    public int Threshold
    {
      get
      {
        return this._threshold;
      }
      set
      {
        this._threshold = value;
      }
    }

    #endregion
  }

Ok, so let’s look at what this is doing.  First the class is used to write to a file.  There are two methods to write to the file.  One is a single write only the other is a batch writer for us to show the use of the circuit breaker pattern.  By default we set the system to perform 50 writes and the threshold is 5 errors, at which point we would expect the circuit to be proverbial broken.  In the attached code you will find a unit test that you can run to see the results for yourself. Needless to say when you run the codebase you should see that there are five errors thrown at which point the codebase effectively shuts down.  Try playing with the threshold.

Overall the pattern shown here can be very effective in integration scenarios but it’s especially effective in batch processes.  In the integration scenario you could have your app try to connect to say an external service and if it fails you want it to return a specified value vs crashing or throwing an exception.  This can be easily accomplished by adjusting how you use the circuit breaker.  All you would need to do is set your boolean variable if your external service is down.