2008-09-17 68 views

回答

41

throw ex;將清除您的堆棧跟蹤。除非你想清除堆棧跟蹤,否則不要這樣做。只需使用throw;

+0

有很多情況下'throw ex'有用嗎? – 2008-09-17 23:47:46

2

你有兩個選擇拋出;或者拋棄原來的例外作爲對新例外的一種內化。取決於你需要什麼。

18

下面是一個簡單的代碼片段,它有助於說明差異。區別在於throw ex會重置棧跟蹤,就好像「throw ex;」這條線是異常的來源。

代碼:

using System; 

namespace StackOverflowMess 
{ 
    class Program 
    { 
     static void TestMethod() 
     { 
      throw new NotImplementedException(); 
     } 

     static void Main(string[] args) 
     { 
      try 
      { 
       //example showing the output of throw ex 
       try 
       { 
        TestMethod(); 
       } 
       catch (Exception ex) 
       { 
        throw ex; 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.ToString()); 
      } 

      Console.WriteLine(); 
      Console.WriteLine(); 

      try 
      { 
       //example showing the output of throw 
       try 
       { 
        TestMethod(); 
       } 
       catch (Exception ex) 
       { 
        throw; 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.ToString()); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 

輸出(注意不同堆棧跟蹤):

System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23

System.NotImplementedException: The method or operation is not implemented.
at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43