Click here to Skip to main content
15,887,304 members
Articles / Programming Languages / C#

Ways of Throwing an Exception in C#

Rate me:
Please Sign up or sign in to vote.
4.70/5 (7 votes)
7 Dec 2010CPOL4 min read 18.8K   10   4
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:

C#
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:

C#
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.

Image 1

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).

Image 2

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

Comments and Discussions

 
Generalgood one - have 5 from me Pin
Pranay Rana18-Dec-10 10:15
professionalPranay Rana18-Dec-10 10:15 
GeneralMy vote of 5 Pin
JH6414-Dec-10 5:37
JH6414-Dec-10 5:37 
GeneralGood but disagree to some extend Pin
Lokanta_b13-Dec-10 3:49
Lokanta_b13-Dec-10 3:49 
GeneralMy vote of 5 Pin
Hiren solanki9-Dec-10 2:18
Hiren solanki9-Dec-10 2:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.