Sung Sung - 2 months ago 11
C# Question

Is there a difference between "throw" and "throw ex"?

There are some posts that asks what the difference between those two are already.

(why do I have to even mention this...)

But my question is different in a way that I am calling "throw ex" in another error god-like handling method.

public class Program
{
public static void Main(string[] args)
{
try
{
// something
}
catch (Exception ex)
{
HandleException(ex);
}
}

private static void HandleException(Exception ex)
{
if (ex is ThreadAbortException)
{
// ignore then,
return;
}

if (ex is ArgumentOutOfRangeException)
{
// Log then,
throw ex;
}

if (ex is InvalidOperationException)
{
// Show message then,
throw ex;
}

// and so on.
}
}


If
try & catch
were used in the
Main
, then I would use
throw;
to rethrow the error.
But in the above simplied code, all exceptions go through
HandleException


Does
throw ex;
has the same effect as calling
throw
when called inside
HandleException
?

Answer

Yes, there is a difference;

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.
Comments