2012-02-20 64 views
1

我想创建新的异常类型来捕获指定日志记录。但我想将int值传递给ctor。怎么做?我尝试:创建新的异常类型

public class IncorrectTimeIdException : Exception 
{ 
    public IncorrectTimeIdException(int TypeID) : base(message) 
    { 
    } 
} 

但我在编译过程中出错。

+5

'message'is not defined;所以,而不是基地(消息)尝试基地(“有什么问题”) – mshsayem 2012-02-20 12:57:55

+4

异常消息(没有双关语意图)应该告诉你到底什么是错的 – BrokenGlass 2012-02-20 12:58:29

+2

请参阅http://blog.gurock.com/articles/creating- dotnet中的定制例外/新异常类型的操作指南 – ken2k 2012-02-20 13:02:41

回答

2
public class IncorrectTimeIdException : Exception 
{ 
    private void DemonstrateException() 
    { 
     // The Exception class has three constructors: 
     var ex1 = new Exception(); 
     var ex2 = new Exception("Some string"); // <-- 
     var ex3 = new Exception("Some string and InnerException", new Exception()); 

     // You're using the constructor with the string parameter, hence you must give it a string. 
    } 

    public IncorrectTimeIdException(int TypeID) : base("Something wrong") 
    { 
    } 
} 
+0

快速的问题。当我构造我的异常时,是否调用类似于DemonstrateException的方法或自然完成? – 2015-03-04 21:47:26

1

该消息告诉你到底是什么问题 - message未定义。

试试这个,它允许你在创建异常提供用户信息:

public IncorrectTimeIdException(string message, int TypeID) : base(message) 
{ 
} 

// Usage: 
throw new IncorrectTimeIdException("The time ID is incorrect", id); 

或可替代这一点,这造成没有消息的异常:

public IncorrectTimeIdException(int TypeID) 
{ 
} 

终于还是这,这会通过预定义的消息创建例外:

public IncorrectTimeIdException(int TypeID) : base("The time ID is incorrect") 
{ 
} 

如果你喜欢你也可以在你的类上声明多个构造函数,所以你可以提供一个构造函数,它在使用预定义的消息的同时提供一个允许你覆盖该消息的构造函数。

2

这里有一些代码可以用来创建一个自定义的异常类,它携带一些额外的数据(在您的情况下是类型ID),并遵循所有用于创建自定义异常的“规则”。您可以根据自己的喜好重新命名异常类和相当无描述的自定义数据字段。

using System; 
using System.Runtime.Serialization; 

[Serializable] 
public class CustomException : Exception { 

    readonly Int32 data; 

    public CustomException() { } 

    public CustomException(Int32 data) : base(FormatMessage(data)) { 
    this.data = data; 
    } 

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

    public CustomException(Int32 data, Exception inner) 
    : base(FormatMessage(data), inner) { 
    this.data = data; 
    } 

    public CustomException(String message, Exception inner) : base(message, inner) { } 

    protected CustomException(SerializationInfo info, StreamingContext context) 
    : base(info, context) { 
    if (info == null) 
     throw new ArgumentNullException("info"); 
    this.data = info.GetInt32("data"); 
    } 

    public override void GetObjectData(SerializationInfo info, 
    StreamingContext context) { 
    if (info == null) 
     throw new ArgumentNullException("info"); 
    info.AddValue("data", this.data); 
    base.GetObjectData(info, context); 
    } 

    public Int32 Data { get { return this.data; } } 

    static String FormatMessage(Int32 data) { 
    return String.Format("Custom exception with data {0}.", data); 
    } 

}