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

前端 未结 10 2591
夕颜
夕颜 2020-11-22 01:08

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

10条回答
  •  佛祖请我去吃肉
    2020-11-22 01:27

    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.

      static void Main(string[] args)
      {
          try
          {
              Method2();
          }
          catch (Exception ex)
          {
              Console.Write(ex.StackTrace.ToString());
              Console.ReadKey();
          }
      }
      
      private static void Method2()
      {
          try
          {
              Method1();
          }
          catch (Exception ex)
          {
              //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
              throw ex;
          }
      }
      
      private static void Method1()
      {
          try
          {
              throw new Exception("Inside Method1");
          }
          catch (Exception)
          {
              throw;
          }
      }
      

提交回复
热议问题