Click here to Skip to main content
Click here to Skip to main content

Tagged as

Ways of Throwing an Exception in C#

, 7 Dec 2010
Rate this:
Please Sign up or sign in to vote.
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
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 :


<span class="kwrd">public</span> <span class="kwrd">void</span> FirstCall()
{
    <span class="kwrd">try</span>
    {

        <span class="kwrd">this</span>.SecondCall();
        Console.WriteLine(<span class="str">"After Exception"</span>);
    }
    <span class="kwrd">catch</span> (Exception ex)
    {
        <span class="kwrd">this</span>.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 :

<span class="kwrd">public</span> <span class="kwrd">void</span> FirstCall()
{
    <span class="kwrd">try</span>
    {
        <span class="kwrd">this</span>.SecondCall();
        Console.WriteLine(<span class="str">"After Exception"</span>);
    }
    <span class="kwrd">catch</span> (Exception ex)
    {
        <span class="kwrd">this</span>.DumpException(ex);
    }
}

<span class="kwrd">public</span> <span class="kwrd">void</span> SecondCall()
{
    <span class="kwrd">try</span>
    {
        <span class="kwrd">this</span>.ThirdCall();
        Console.WriteLine(<span class="str">"Second Call"</span>);
    }
    <span class="kwrd">catch</span> (Exception ex)
    {
        <span class="kwrd">this</span>.DumpException(ex);
        <span class="kwrd">throw</span> ex;
    }
}

<span class="kwrd">public</span> <span class="kwrd">void</span> ThirdCall()
{
    <span class="kwrd">try</span>
    {
        <span class="kwrd">this</span>.GenerateException();
        Console.WriteLine(<span class="str">"Third Call"</span>);
    }
    <span class="kwrd">catch</span> (Exception ex)
    {
        <span class="kwrd">this</span>.DumpException(ex);
        <span class="kwrd">throw</span>;
    }
            
}

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.

License

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

Share

You may also be interested in...

About the Author

Abhishek Sur
Architect
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.
 
Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
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
Follow on   Twitter   Google+

Comments and Discussions

 
Generalgood one - have 5 from me PinmemberPranay Rana18-Dec-10 10:15 
GeneralMy vote of 5 PinmemberJH6414-Dec-10 5:37 
GeneralGood but disagree to some extend PinmemberLokanta_brahmachari13-Dec-10 3:49 
GeneralMy vote of 5 PinmemberHiren Solanki9-Dec-10 2:18 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 7 Dec 2010
Article Copyright 2010 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid