Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i was unable to understand difference between throw and throw ex .what happens if i use throw or throw ex???


C#
try
{
}
catch(Exception ex)
{
    throw ex;
}

try
{
}
catch(Exception ex)
{
    throw;
}
Posted
Updated 27-Jan-15 4:21am
v2

Further to solution 1 there is another discussion of when to use / not use throw ex; here[^] - it includes explanations of what is happening under the covers

[EDIT]
I'm a great believer in empirical evidence so I did the following to demonstrate what most people are on about...
I created a WinForm with a multi-line text box and a button then added the following code
C#
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        Level1();   //This is line 17
    }
    catch (Exception ex)
    {
        this.textBox1.Text = ex.StackTrace;
    }
}
private void Level1()
{
    try
    {
        Level2();
    }
    catch (Exception ex)
    {
        throw ex;   //This is line 32
    }
}
private void Level2()
{
    try
    {
        Level3();
    }
    catch (Exception ex)
    {
        throw ex;  //This is line 43
    }
}
private void Level3()
{
    throw new Exception("Test");   //This is line 48
}

When I run the program and click the button, I get this text in the textbox (edited only to remove the path to my temporary projects folder)
Quote:
at WindowsFormsApplication1.Form1.Level1() in WindowsFormsApplication1\Form1.cs:line 32
at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in WindowsFormsApplication1\Form1.cs:line 17
I then changed the Level1 and Level2 functions as follows (i.e. remove the "ex" from the throw
C#
private void Level1()
{
    try
    {
        Level2();
    }
    catch (Exception ex)
    {
        throw;   //This is line 32
    }
}
private void Level2()
{
    try
    {
        Level3();
    }
    catch (Exception ex)
    {
        throw;   //This is line 43
    }
}
and re-ran the program. This time the text box contained
Quote:
at WindowsFormsApplication1.Form1.Level3() in WindowsFormsApplication1\Form1.cs:line 48
at WindowsFormsApplication1.Form1.Level2() in WindowsFormsApplication1\Form1.cs:line 43
at WindowsFormsApplication1.Form1.Level1() in WindowsFormsApplication1\Form1.cs:line 32
at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in WindowsFormsApplication1\Form1.cs:line 17

As you can see the latter version ("throw") gives me information in StackTrace all the way down to the original exception whereas "throw ex" only gives me information back to the last throw ex;.
I would have had the same difference in information if I'd used textBox1.Text = ex.ToString(); but I wanted to draw attention to the fact it is the StackTrace that is affected.

I hope this helps to clear up for you the differences in opinions being expressed here and on the various links provided in the solutions.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 27-Jan-15 23:22pm    
Which of the answers do you thing explains it? I think all of them are bad. Please see my other comments and my answer.
—SA
Alan N 28-Jan-15 8:06am    
There's one fairly common situation not covered in your tests which may be the reason for the OP's question. When a throw and rethrow are within the same method the stack trace is always changed by the rethrow to indicate the line where the flow of execution left the method. In the example method a bare 'throw' and a qualified 'throw exc' behave identically and show an exception apparently thrown at location 2.

public void WTFMethod() {
try {
throw new Exception(); // location 1
} catch (Exception exc) {
Console.WriteLine(exc);
throw; // location 2
}
}
CHill60 28-Jan-15 8:10am    
Fair point and well made. This is actually mentioned in one of the discussions on the link I provided in my original answer. I didn't want to complicate the simple example which was only posted in response to SA's comment "Somebody made up this thing with stack trace"
Please have a look here:
http://www.dotnetperls.com/throw[^]
 
Share this answer
 
Comments
TheRealSteveJudge 28-Jan-15 2:58am    
Thank you for voting down.
CHill60 28-Jan-15 7:08am    
I've countered it and updated my solution with empirical evidence
TheRealSteveJudge 28-Jan-15 8:36am    
Thank you!
Throw ex resets the stack trace. Throw preserves the stack trace.
Throw ex throws a new exception, so the stack trace changes and is reset.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 27-Jan-15 23:21pm    
Somebody made up this thing with stack trace and you repeat it. I already saw such "answers" around.

Do you mean call stack? Did you look at it at the point of exception catch? If not, please do it. There is no difference. The whole idea of the exception is that they jump over the call step ("long jump"). What is the difference what the type of the exceptions? Exceptions form their own, additional stack, otherwise the mechanism would not "know" where to propagate exception, from one catch point to another.

Sorry, this is not a valid answer. Pleas see Solution 4.

But maybe I miss something important, then please explain it.

—SA
In your case, they do exactly the same thing: re-throw the same very exception, the one you just caught. As such, both makes no sense. You only need to re-throw exception if you do it selectively, on some condition. What is shown in your code should never even be done; it has no effect except wasting of some CPU time (which can be considerable if is done repeatedly).

First way of re-throwing is usually needed when you add some useful information to the exception. Then you re-throw different instance of exception object, or exception of different type. (That's why your code makes no sense at all.) Typically, you catch "technical" exception and through "semantic" exception. For example, you catch exception of integer divide by zero, because of the data entered by the user. You catch it and re-through your own exception type which carry the information based on analysis of data and put some semantic data in it: what's wrong with data. This example is a bit artificial, but I made it up just to explain the idea.

The second form of re-throwing simply helps you to make the handling conditional. Let's say, you analyze some data and decide to either handle exception (work around exceptional situation). If this cannot be done, you the same exception up stack by re-throwing it.

—SA
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900