我目前正在學習C#,但是我被困在某些東西上,而我找不到解決方案。
我想創建自己的Exception類。如何創建一個自定義的C#異常?
這個異常被稱爲「InvalidNumberException」,它檢查一個數是否等於5.我知道它可能看起來有點愚蠢,但我只需要了解有關創建自定義異常的想法。
到目前爲止,我在MSDN上發現,用於創建例外,我需要這四個構造函數:
public class InvalidNumberException : System.Exception
{
public InvalidNumbertException() : base() { }
public InvalidNumberException(string message) : base(message) { }
public InvalidNumberException(string message, System.Exception inner) : base(message, inner) { }
// A constructor is needed for serialization when an
// exception propagates from a remoting server to the client.
protected InvalidNumberException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) { }
}
,但我不知道如何實現從輸入的數字在這個類中的方法或構造控制檯等於5,如果不是,則會引發異常。
如果有人能幫助我,我將不勝感激。
OT,你不應該自己寫四個構造函數。只需實施你需要的。 ''public class InvalidNumberException:Exception {}'should should work if if you do you all-to要做的事就是拋出new InvalidNumberException();' – 2011-03-15 22:18:12
值得注意的是,除非真的需要,否則不應該創建自定義異常。首先仔細想一想。請參閱http://blogs.msdn.com/b/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx – 2013-01-14 13:03:07