2013-05-13 34 views
0

我不確定這是否可能。 (我認爲它應該)。如果不按照以下方式拋出新的產品,是否有可能抓住客戶的觀點?在.NET中沒有新投入的自定義異常

 try 
     { 
      //Some logic which throws exception 
     } 
     catch (Exception) 
     { 
      throw new CustomException(); 
     } 

我想什麼有如下:

 try 
     { 
      //Some logic which throws exception 
     } 
     catch (CustomException) 
     { 
      // Handles the exception 
     } 

我已經嘗試了上面,但它不是直接抓我CustomException。我不得不做「throw new CustomException()」這是不理想的。我究竟做錯了什麼?

我的自定義異常類看起來如下:

[Serializable] 
    public class CustomException : Exception 
    { 
     public CustomException() 
      : base() { } 

     public CustomException(string message) 
      : base(message) { } 

     public CustomException(string format, params object[] args) 
      : base(string.Format(format, args)) { } 

     public CustomException(string message, Exception innerException) 
      : base(message, innerException) { } 

     public CustomException(string format, Exception innerException, params object[] args) 
      : base(string.Format(format, args), innerException) { } 

     protected CustomException(SerializationInfo info, StreamingContext context) 
      : base(info, context) { } 
    } 

感謝,

+1

問題是什麼?你的第二個代碼片段看起來很好。 – dlev 2013-05-13 08:13:25

+0

對不起,只是編輯我的問題。 – daehaai 2013-05-13 08:14:54

+1

代碼是否拋出CustomException?或者是拋出一個不同的異常,你想變成一個CustomException?如果是後者,那麼第二種方法就行不通了。 – dlev 2013-05-13 08:16:12

回答

1

catch條款不會自動轉換例外,這不是它的工作方式。它將過濾器try子句中引發的異常。通過使用

catch (CustomException e) 
{ 
} 

你正在處理CustomException實例或派生的異常clasess的實例 - 換句話說,只有當try塊拋出任何這些的catch子句就會執行。因此,如果例如FileNotFoundException被拋出,您的catch子句將不會被執行,並且代碼將導致未處理的FileNotFoundException

如果您的意圖是讓您的代碼僅丟失CustomException,以避免try塊中可能出現的所有可能的異常情況,則需要捕獲所有這些異常。一個一般catch塊會爲你做這個:

catch (Exception e) // catches exceptions of any type 
{ 
    throw new CustomException(e.Message, e); 
} 

需要注意的是,我們通過在CustomException構造原始異常(消息是任選重複使用,你可以將你自己的)。這是一個經常被忽略但非常重要的做法,因爲通過傳遞內部異常,您將在日誌中獲得完整的堆棧跟蹤,或者在調試時獲得更好的問題信息。