Ways of Throwing 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 to handle this in their own code. Lets 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.

Download Sample Code - 30 KB




Exception Propagation

As this is very common practice to handle exception inside catch block, yet you often need 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 implicitely, 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 ? Lets 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 nest within another. Each of the method call 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 lets see the output from FirstCall through the call set and demonstrate what is modified by these different call sets.

1. Throw

 Throw implicitely 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.

Lets 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 behaviour (maintaining the whole stack).

Now If 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 same as throwing a new exception object altogether and specifying all the information in its constructor.

Download Sample Code - 30 KB






I hope this clears the doubt. Thank you for reading.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

4 comments:

Anonymous said...

Nice article....quite nested calls but well explained, Thnx!!!!... - Sunny

Zenwalker said...

Nice article abhi. Recently i bumped into the same topic while coding. Been liking the throw since then ;)
.Net is crazy n tricky at times :D

Abhishek Sur said...

@Zenwalker
Yes budd. Its been tricky at many places as language designer thought to make it. Weird how IL treats two statements.... :)

Anonymous said...

Beneficial info and excellent design you got here! I want to thank you for sharing your ideas and putting the time into the stuff you publish! Great work!

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!