2008-09-17 14 views

Respuesta

41

throw ex; borrará su stacktrace. No hagas esto a menos que quieras borrar la pila stack. Solo use throw;

+0

¿hay muchas circunstancias en las que 'throw ex' es útil? –

+0

Nunca he visto uno, aunque podría haberlo. Como se menciona a continuación, he oído de adjuntarlo a la innerecepción, pero no puedo pensar en ninguna razón por la que quiera destruir su rastro de pila. – GEOCHET

2

Tiene dos opciones; o arrojar el original excepcional como una innerecepción de una nueva excepción. Dependiendo de lo que necesites

18

Aquí hay un fragmento de código simple que ayudará a ilustrar la diferencia. La diferencia es que throw ex restablecerá el seguimiento de la pila como si la línea "throw ex;" fuera la fuente de la excepción.

Código:

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

salida (notar la diferente seguimiento de la pila):

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

Cuestiones relacionadas