BlackWaspTM
C# Programming
.NET 1.1+

Throwing Exceptions in C# (2)

The thirty-fifth part of the C# Fundamentals tutorial completes an investigation of exception handling. In this article we will consider the throwing of exceptions to report error conditions. This includes the use of standard and custom exception types.

Re-Throwing Exceptions

When you trap an exception in a catch block, the exception is considered to have been processed and code execution continues normally. Sometimes you will want to catch the exception but still have it thrown to be caught again. For example, you may catch and log exceptions and then re-throw them to be handled by the calling function.

When an exception is thrown explicitly using the previous syntax, a new exception object is created. This contains only the basic information that you specify; information such as the stack trace of the original exception is lost. To re-throw the original exception and retain all additional information, use the throw command without specifying an exception object:

throw;

The following sample demonstrates how this syntax is used. For simplicity, the methods called are not defined so this code cannot be directly executed.

static void Main(string[] args)
{
    try
    {
        InitialiseData(args[0]);
        SaveToDisk();
    }
    catch (Exception ex)
    {
        // Log the details of any exception and re-throw
        LogException();
        throw;        
    }
}

Using the InnerException Property

In the previous article in the tutorial, I described the InnerException property, which can be used to hold the details of an initial exception that caused a further exception to be thrown. This mechanism is useful when you wish to throw one exception in response to another without losing the original problem's details.

The following example extends the re-throw sample above by throwing a FileNotFoundException with a new error message and the caught exception's details in the InnerException property.

static void Main(string[] args)
{
    try
    {
        InitialiseData(args[0]);
        SaveToDisk();
    }
    catch (Exception ex)
    {
        // Log the details of any exception and re-throw
        LogException();
        throw new System.IO.FileNotFoundException("Invalid file argument", ex);
    }
}

NB: The above code is provided as an example of setting the InnerException property. It is not good practice to use a catch-all and throw a new exception as this can mask serious problems.

9 April 2007