What is difference between throw and throw ex?

 Posted by Rajni.Shekhar on 6/27/2012 | Category: C# Interview questions | Views: 5443 | Points: 40
Answer:

When you use throw ex to throw exception, it will update stack trace but in throw it will not update stack trace.

Example:
Class cls

{
public static void Main(string[] args)
{
try
{

function3();
Console.WriteLine("Catch Ex"); Console.ReadLine();

}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace); Console.ReadLine();
}
}

public static void function3()
{
try
{
function2();
}
catch (Exception ex)
{
throw;
}
}
public static void function2()
{
try
{
function1();
}
catch (Exception ex)
{
throw;
}
}
public static void function1()
{
try
{
int i = 0;
int j = 2 / i;
}
catch (DivideByZeroException ex)
{
throw;
}
}
}


Source: HCL | Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Siddh on: 1/31/2017 | Points: 10
Nice Explanations, after long time I have cleared the concept about difference between Throw and Throw ex,
I have tried to clear the concept and learn number of blogs from internet but this blog help me to clear my concept.
thank you very much.
God bless you

Login to post response