2008-09-17 18 views

risposta

41

throw ex; cancellerà lo stacktrace. Non farlo a meno che non intendi cancellare lo stacktrace. Basta usare throw;

+0

ci sono molte circostanze in cui 'a due ex' è utile? –

+0

Non ne ho mai visto uno, anche se potrebbe esserci. Come ho detto di seguito, ho sentito di averlo collegato alla soprannaturale, ma non riesco a pensare a nessuna ragione per cui vorresti distruggere la traccia dello stack. – GEOCHET

2

Hai due opzioni di lancio; o lanciare l'eccezionale originale come una sorta di soprannaturale di una nuova eccezione. A seconda di cosa hai bisogno.

18

Ecco uno snippet di codice semplice che aiuterà a illustrare la differenza. La differenza è che throw ex ripristinerà la traccia dello stack come se la riga "throw ex;" fosse la fonte dell'eccezione.

Codice:

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(); 
     } 
    } 
} 

uscita (notare il diverso stack trace):

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

Problemi correlati