2016-02-12 27 views
1

我已經解決了這個問題,我發佈了。區分原始System.Exception並拋出新的Exception/ApplicationException?

對於瘋狂調用的方法,是否可以區分原始System.Exception(即throw ex;)和新的Exception(即throw new Exception("Specific error", ex);)還是新的ApplicationException

public void InsertNewCar() 
{ 
    try 
    { 
     Car myCar = new Car(); 
     myCar.Insert(); 
    } 
    catch (Exception ex) 
    { 
    if (/* This ex is the New Exception */ 
     alert(somethingMissingMsg); 
    } 
    else /* This is the original exception */ 
    { 
     alert(Something wrong generic error); 
    } 
} 

public void Insert() 
{ 
    try 
    { 
     SqlHelper.ExecuteNonQuery(ConnString, CommandType.Text, sqlInsert); 
    } 
    catch (SqlException ex) 
    { 
     if (ex.Number == 515) 
     { 
      throw new Exception("Missing something", ex); 
      //throw new ApplicationException("Missing something", ex); 
     } 
     else 
     { 
      throw ex; 
     } 
    } 
} 

謝謝。

+0

[訂購catch塊時,試圖處理異常(可能的重複http://stackoverflow.com/questions/15609597/order-catch-blocks-when-try-to-handle-an-exception )@Stephen – Stephen

+0

,這不是重複的。訂購catch塊如何與此相關?我的問題與實際異常無關,但如何區分接收異常的方法中的異常。 – rbhat

+0

我剛纔明白你的問題....閱讀對方的回答評論後... – Stephen

回答

0

結束了使用此:

public void InsertNewCar() 
{ 
    try 
    { 
     Car myCar = new Car(); 
     myCar.Insert(); 
    } 
    catch (Exception ex) 
    { 
    if (ex is ApplicationException) 
     alert("Something missing Msg"); 
    else /* This is the original exception */ 
     alert("Something wrong generic error"); 
} 

public void Insert() 
{ 
    try 
    { 
     SqlHelper.ExecuteNonQuery(ConnString, CommandType.Text, sqlInsert); 
    } 
    catch (SqlException ex) 
    { 
     if (ex.Number == 515) 
     { 
      throw new ApplicationException("Missing something", ex); 
     } 
     else 
     { 
      throw ex; 
     } 
    } 
} 
+0

如果你想重新拋出異常,則可能需要使用'throw',而不是'拋ex',並趕上你的您的例外與多個特定catch塊:只使用'趕上(異常前)'的情況下,你不預期 – Stephen

1

可以指定你想趕上(介意排序)什麼樣的異常。異常的InnerException屬性可能包含導致當前異常的其他信息。

try 
{ 
    MethodThatBlowsUp(); 
} 
catch (ApplicationException appex) 
{ 
    //handle 
} 
catch (Exception ex) 
{ 
    //handle 
} 
+0

謝謝,但我的問題是不相關的實際例外,但如何在方法例外區分是正在接收的例外。 – rbhat

相關問題