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
private void button1_Click(object sender, EventArgs e)
{
try
{
Level1();
}
catch (Exception ex)
{
this.textBox1.Text = ex.StackTrace;
}
}
private void Level1()
{
try
{
Level2();
}
catch (Exception ex)
{
throw ex;
}
}
private void Level2()
{
try
{
Level3();
}
catch (Exception ex)
{
throw ex;
}
}
private void Level3()
{
throw new Exception("Test");
}
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
private void Level1()
{
try
{
Level2();
}
catch (Exception ex)
{
throw;
}
}
private void Level2()
{
try
{
Level3();
}
catch (Exception ex)
{
throw;
}
}
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.