2016-09-14 25 views
-1

我需要定製系統異常而不使用用戶定義的異常類。自定義系統異常實例傳遞兩個參數

以下是我的要求。

String ErrorMessage=""; 
Exception e= new Exception (ErrorMessage); 

然後我需要拋出errorMessage字符串與一個整數參數爲上層在我的項目。

那麼有人請讓我知道,如果我可以自定義系統異常實例傳遞兩個參數(整數值和errorMessage字符串)?

+1

你不能。你所能做的就是對它進行子類化並添加一個帶有兩個參數的新構造函數。 –

+0

平心而論,你*真的不應該拋出'System.Exception'。這基本上就是所有託管異常的祖父,它不應該直接拋出,而且幾乎不會被處理。 **正確**的方式來做你想做的就是繼承現有的異常並在那裏添加你的屬性和構造函數。 –

回答

-1

您可以創建一些自定義Exception類並使用相同的代碼TryCatch拋出它。但在上層,您可以使用您的自定義類型不通過泛型異常捕獲。

Try 
{ 
    //Your try code Here 
    if(/*Something Happens*/) 
    { 
     throw new YourCustomExceptionClass("Message"); 
    } 
    else 
    { 
     throw new AnotherCustomExceptionClass("Other Message"); 
    } 
} 
Catch(YourCustomExceptionClass err) 
{ 
    //This will be a type of exception 
} 
Catch(AnotherCustomExceptionClass err) 
{ 
    //This will be another type of Exception 
} 
+0

這個問題*明確表示他不打算創建一個新的異常類。 – Servy

+0

我想僅使用c#系統異常類來傳遞參數列表或數組參數。因爲我的項目中有一些限制,所以無法使用自定義異常類。 – Gobi

0

這根本不可能。

你唯一的選擇是創建一個新類,它繼承自System.Exception或其他一些異常類,並在那裏添加你需要的任何東西。

如果你不能或不會這樣做,那麼你不能做你想做的。

0

一些真實的例子:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ExceptionExamples 
{ 
    public static class Error 
    { 
     [Serializable] 
     public class RegistryReadException : Exception 
     { 
      /// <summary> 
      /// Message template 
      /// </summary> 
      static string msg = "Can't parse value from Windows Registry.\nKey: {0}\nValue: {1}\nExpected type: {2}"; 

      /// <summary> 
      /// Can't read value from registry 
      /// </summary> 
      /// <param name="message"></param> 
      public RegistryReadException(
       string message) 
       : base(message) { } 

      /// <summary> 
      /// Can't read value from registry 
      /// </summary> 
      /// <param name="key">Key path</param> 
      /// <param name="value">Real value</param> 
      /// <param name="type">Expected type</param> 
      public RegistryReadException(
       string key, string value, Type type) 
       : base(string.Format(msg, key, value, type.Name)) { } 
     } 
    } 
}