I was trying to understand the differences between throw & throw ex. In order to assist my learning, I did some research into the theory, which led me to the following links:
Summarizing the above points the difference is:-
throw re-throws the exception that was caught, and preserves the stack trace. throw ex throws the same exception, but resets the stack trace to that method.
So I went ahead & created a demo application for the same to see the difference in action.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Calc c = new Calc();
c.Test();
}
}
class Calc
{
public void Test()
{
try
{
int a = 10;
int b = 10;
int c = 10 / (a - b);
}
catch (Exception ex)
{
throw; //throw statement
}
}
}
}
This gives me the output as:-
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at ConsoleApplication1.Calc.Test() in C:\kgn\personal\workspace\ConsoleApplication1\ConsoleApplication1\Program.cs:line 31 at ConsoleApplication1.Program.Main(String[] args) in C:\kgn\personal\workspace\ConsoleApplication1\ConsoleApplication1\Program.cs:line 14
Now replaced the throw with throw ex.
class Calc
{
public void Test()
{
try
{
int a = 10;
int b = 10;
int c = 10 / (a - b);
}
catch (Exception ex)
{
throw ex; // throw ex statement
}
}
}
This gives the output as:-
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at ConsoleApplication1.Calc.Test() in C:\kgn\personal\workspace\ConsoleApplication1\ConsoleApplication1\Program.cs:line 31 at ConsoleApplication1.Program.Main(String[] args) in C:\kgn\personal\workspace\ConsoleApplication1\ConsoleApplication1\Program.cs:line 14
If I see the exception messages, they are both identical.
So where is the difference?
I agree surely there is a difference, but why am I not seeing it? What point am I missing here?
The problem that you're not seeing is that the possible throw locations you're working with are so close together as to be indistinguishable when the stack trace is collected.
Try instead:
The
throw;
variant will show youDeeper
in the stack trace.throw ex;
will only showTest
as the deepest level.