This is sort of a sequel to my Cunning Design post, that I made a while ago. It is not necessary that you read the old post before you read this one, but if you do I think you will appreciate this one a bit more. Anyway, take a look at the following cunning exception handling code:

      const string exceptionMessage = "An error message with " +

                        "multiple possible reasons of failure.";

      try

      {

            bool exceptionThrown = false;

 

            try

            {

                  // Some logic here, calling a couple of methods

            }

            catch (ArgumentException)

            {

                  exceptionThrown = true;

            }

            catch (SomeCustomException)

            {

                  exceptionThrown = true;

            }

 

            if (exceptionThrown)

            {

                  throw new OtherCustomException(exceptionMessage);

            }

      }

      catch (Exception ex)

      {

            throw new OtherCustomException(exceptionMessage, ex);

      }

Great stuff eh? Let's throw exceptions, catch them and then use boolean flags to determine when another exception should be thrown; and lets do all this within a try block. Wait, I have a better idea. Lets have every single method return a boolean that indicates success or failure and an out parameter that will be the error message for when the method failed. No, no wait I have an even better idea. Instead of the string output parameter lets have the methods accepting a StringBuilder to which they will append every possible error message and lets do that regardless of whether the method succeeded or failed. We should and up with an interesting message after a few method calls ...

Something went wrong. It could be any of the following reasons:
- Parameter x can't be null.
- Parameter x can't be empty.
- Object was disposed.
- Run out of memory.
- Run out of hard-drive space.
- Run out of milk.
- You suck.

What is quite funny is that if you navigate through the methods that are called within the inner try block, you will encounter exceptions being thrown with messages matching parts of the exceptionMessage string. In other words, when this was coded they had a look at some of the exceptions that could be thrown and copy-pasted their error messages into exceptionMessage.

I actually came about this piece of code when I was looking into a problem that resulted in a message box with the contents of exceptionMessage showing. After trying to figure out exactly which exception was being thrown for about half an hour (couldn't debug unfortunately), it turns out that at some point data was saved to the database and a unique constraint was being violated. Made my day ...