throw ex vs throw

2015年1月22日 星期四

寫了這麼久的程式,都沒特別注意到這二者的差別
簡單來說throw 會多一項原始執行錯誤行號。


  • 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 {
   ThrowException1(); // line 19
  } catch (Exception x) {
   Console.WriteLine("Exception 1:");
   Console.WriteLine(x.StackTrace);
  }
  try {
   ThrowException2(); // line 25
  } catch (Exception x) {
   Console.WriteLine("Exception 2:");
   Console.WriteLine(x.StackTrace);
  }
 }

 private static void ThrowException1() {
  try {
   DivByZero(); // line 34
  } catch {
   throw; // line 36
  }
 }
 private static void ThrowException2() {
  try {
   DivByZero(); // line 41
  } catch (Exception ex) {
   throw ex; // line 43
  }
 }

 private static void DivByZero() {
  int x = 0;
  int y = 1 / x; // line 49
 }

輸出結果
Exception 1(throw):
at UnitTester.Program.DivByZero() in \Dev\UnitTester\Program.cs:line 49
at UnitTester.Program.ThrowException1() in \Dev\UnitTester\Program.cs:line 36
at UnitTester.Program.TestExceptions() in \Dev\UnitTester\Program.cs:line 19
Exception 2(throw ex):
at UnitTester.Program.ThrowException2() in \Dev\UnitTester\Program.cs:line 43
at UnitTester.Program.TestExceptions() in \Dev\UnitTester\Program.cs:line 25

0 意見: