Thursday, 31 March 2016

What is the difference between “throw ex” and “throw” methods in C#?

  • “throw ex” will replace the stack trace of the exception with stack trace info of re throw point.
  • “throw” will preserve the original stack trace info.
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.
    }
}

No comments:

Post a Comment