Programmers' Day++ Special

Happy Programmers' Day++ everyone!  Wikipedia has some more information on this holiday.  I forgot that this was a leap year, so the real Programmers' Day was yesterday... We'll just increment that day by one (hence the ++ operator) and continue on with our holiday.  Now on to some free ways to celebrate:

1)  For the nerdier IT folks (is that redundant?) you could check out Unix for the Beginning Mage.

2)  For the non-programmers, it's never too late to learn programming with the interactive Codeacademy website.

3)  For Windows programmers, try out the new Visual Studio 2012 Express that was released yesterday.

I'm going to be trying out method 3 over the next week and will be posting some information about my setup and initial experiences during that time.

Rethrowing Exceptions

How to Rethrow an Exception


When catching an exception in a language like C#, sometimes it's helpful to rethrow the exception to let some outer calling method handle the exception.

Example 1 (incorrect method):
catch (Exception ex)
{
    throw ex;
}

Example 2 (correct method):
catch (Exception ex)
{
    throw;
}

In the first example, a new exception is made based on the caught exception, but this new exception loses the stack trace of the original exception.  The second example is truly rethrowing the original exception and the stack trace is preserved.

Customizing the Rethrown Exception


In many cases, a programmer will want to add some data to an exception before it's rethrown.  There are two main methods for doing this.

Method 1:
catch (Exception ex)
{
    throw new CustomException("This is some custom data", ex);
}

Method 2:
catch (Exception ex)
{
    ex.Data.Add("CustomData", "This is some custom data");
    throw;
}

In the first method, a new Exception type is created that contains the original exception.  This is handy for cases where the logical exception has changed and the name should therefore change to reflect this.

In most cases, the type of exception is the same, but the current catch block is simply adding some extra debug information to the exception.  In this case, use the second method shown above.  Here we are simply adding some data to the current exception before rethrowing it.  This data is being added to a Dictionary, and is therefore structured as a key/value pair.  Both the key and value are of type object, but the key should be a string when possible.