What is difference between throw and throw ex?

 Posted by Rajni.Shekhar on 6/27/2012 | Category: C# Interview questions | Views: 3090 | 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

Login to post response