Monday, February 18, 2013

Is there a difference between “throw” and “throw ex”?


Throw: It propagates the full stack information to the caller,
                      When you use the throw with an empty parameter, you are re-throwing the last exception. Or rethrows the original exception and preserves its original stack trace.
Sample:


static void Main(string[] args)
{
  try
  {
     Method2();
  }
  catch (Exception ex)
  {
     Console.WriteLine(ex.StracTrace.ToString());
     Console.ReadLine();
  }
}

static void Method2()
{
  try
  {
     Method1();
  }
  catch (Exception ex)
  {
     throw;
  }
}

static void Method1()
{
  try
  {
     throw new Exception ("This is thrown from Method1");
  }
  catch (Exception ex)
  {
     throw;
  }
}

Throw ex:

Sample:


static void Main(string[] args)
{
  try
  {
     Method2();
  }
  catch (Exception ex)
  {
     Console.WriteLine(ex.StracTrace.ToString());
     Console.ReadLine();
  }
}

static void Method2()
{
  try
  {
     Method1();
  }
  catch (Exception ex)
  {
     throw ex;
  }
}

static void Method1()
{
  try
  {
     throw new Exception ("This is thrown from Method1");
  }
  catch (Exception ex)
  {
     throw;
  }
}




Summary:


Reference link : http://dotnetinterviewquestion.wordpress.com/2012/06/06/c-training-difference-between-throw-and-throw-ex/