2008-09-17 6 views

답변

41

throw ex; 스택 추적이 지워집니다. stacktrace를 지우지 않는 한이 작업을 수행하지 마십시오. 그냥 사용 throw;

+0

'throw ex'가 유용한 많은 경우가 있습니까? –

+0

나는 있을지 모르지만 나는 그것을 본 적이 없다. 아래에 설명했듯이, 나는 그것을 innerexception에 붙이는 것에 대해 들어 왔지만 스택 추적을 없애고 싶지는 않습니다. – GEOCHET

2

두 가지 옵션이 있습니다. 또는 예외적 인 예외를 새 예외의 구현으로 던지십시오. 필요한 것에 따라.

18

다음은 차이를 설명하는 데 도움이되는 간단한 코드 조각입니다. 차이점은 예외를 throw하는 것이 "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