65.9K
CodeProject is changing. Read more.
Home

Ways of Throwing an Exception in C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.70/5 (7 votes)

Dec 7, 2010

CPOL

4 min read

viewsIcon

19182

Here are the ways to throw an exception in C#

Exception handling is very common for everyone. Exceptions are runtime errors which might be caused by some operation illegal to the application. .NET provides a good Exception Model (even though Microsoft wants to change this model) using try/catch which lets us to deal with runtime exceptions from our code.

It is stated that you write your code that might generate an exception inside try block, write the logic which handles the exception generated within the catch block (like logging, notifying etc.), where catch block can overload. Also you should keep in mind, it is recommended to wrap your code in try / catch only if you think you can handle the exception, if you cannot, it is better to leave apart the exception and let the caller handle this in their own code. Let's take an example:

public void FirstCall()
{
    try
    {

        this.SecondCall();
        Console.WriteLine("After Exception");
    }
    catch (Exception ex)
    {
        this.DumpException(ex);
    }
}

So in the above code, the Try/catch block is introduced to implement the code with exception handling. I am using DumpException which writes the exception to the Console.

Exception Propagation

As this is very common practice to handle exception inside catch block, yet you often need an exception to propagate from your code to one who calls it, so that subsequent exception can be avoided (based on the sensitivity of the exception). CLR allows you to throw an exception inside the catch block implicitly, so that when you use throw directly inside the catch block, it rethrows the same exception object to the caller preserving the caller stack intact. Now what does it mean exactly? Let's demonstrate the same with code:

public void FirstCall()
{
    try
    {
        this.SecondCall();
        Console.WriteLine("After Exception");
    }
    catch (Exception ex)
    {
        this.DumpException(ex);
    }
}

public void SecondCall()
{
    try
    {
        this.ThirdCall();
        Console.WriteLine("Second Call");
    }
    catch (Exception ex)
    {
        this.DumpException(ex);
        throw ex;
    }
}

public void ThirdCall()
{
    try
    {
        this.GenerateException();
        Console.WriteLine("Third Call");
    }
    catch (Exception ex)
    {
        this.DumpException(ex);
        throw;
    }
            
}

So I have created a number of methods, FirstCall, SecondCall and ThirdCall such that one method nests within another. Each of the method calls is made inside the try/catch block. The final call to GenerateException throws an exception.

Please note, in ThirdCall, the catch block uses blind throw keyword. In SecondCall, the catch introduces throw ex. Now let's see the output from FirstCall through the call set and demonstrate what is modified by these different call sets.

1. Throw

Throw implicitly rethrows the existing exception which caused the call to catch to the caller. We call this as blind call as we do not need to specify the exception object.

2. Throw ex

Throw ex is another way of throwing an exception, but in this case, the exception object yet transferred will hold the reference of this line where you thrown the exception rather than the place which actually generates the exception.

Let's see how the DumpException writes the output in the console for these cases.

Now, if you view the StackTrace, the Exception Propagation actually builds the exception stack whenever the object is propagated from one place to another. We dump the initial Red section from inside the ThirdCall, which lists the line number 68 being the actual exception, and Line No 41 is where the GenerateException is called from. The exception object holds stack information of both of them.

In the Yellow section, you can see, it had added the SecondCall method as well to the StackTrace. This is because we passed the exception object from ThirdCall using blind Throw call. Thus you can see the blind Throw actually preserves the stack information.

In the Cyan section, we only list the SecondCall as LineNo 33. My Line No 33 is actually where we specified Throw ex. Hence you can see using Throw ex actually creates the Exception on the same line rather than holding the entire Stack information.

Hence, you might say it is better to use blind throw rather than Throw ex. Blind throw creates the same output as if there is no catch handler. Means if you omit the try/catch block, the exception will propagated using the blind throw behavior (maintaining the whole stack).

Now if you let me quickly show you these in terms of IL. After I open ILDASM tool and load the assembly, and investigate the two methods, one with blind throw, and another with throw ex, the two. In the image, you can see the IL writes rethrow when you write throw in C#, whereas IL writes throw when you write Throw ex. Basically Rethrow in IL means the own local stack variable will be rethrown outside the call. Throw on the other hand creates an exception object and tries to assign the values from exception object you pass and then throws the exception from the same point. This is the same as throwing a new exception object altogether and specifying all the information in its constructor.

I hope this clears the doubt. Thank you for reading.