您必须每次都创建新的异常,因为这就是 catch() 在 try ... catch 块中捕获特定异常类型的工作方式。但我真的很喜欢通过 C# 书从 CLR 采取的下一种方法:
public abstract class ExceptionArgs
{
public string Message { get { return string.Empty; } }
}
[Serializable]
public class Exception<TExceptionArgs> : Exception, ISerializable
where TExceptionArgs : ExceptionArgs
{
private const String c_args = "Args"; // For (de)serialization
private readonly TExceptionArgs m_args;
public TExceptionArgs Args { get { return m_args; } }
public Exception(String message = null, Exception innerException = null)
: this(null, message, innerException) { }
public Exception(TExceptionArgs args, String message = null,
Exception innerException = null)
: base(message, innerException) { m_args = args; }
[SecurityPermission(SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter)]
protected Exception(SerializationInfo info, StreamingContext context)
: base(info, context)
{
m_args = (TExceptionArgs)info.GetValue(c_args, typeof(TExceptionArgs));
}
[SecurityPermission(SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(c_args, m_args);
base.GetObjectData(info, context);
}
public override String Message
{
get
{
String baseMsg = base.Message;
return (m_args == null) ? baseMsg : baseMsg + " (" + m_args.Message + ")";
}
}
public override Boolean Equals(Object obj)
{
Exception<TExceptionArgs> other = obj as Exception<TExceptionArgs>;
if (obj == null) return false;
return Object.Equals(m_args, other.m_args) && base.Equals(obj);
}
public override int GetHashCode() { return base.GetHashCode(); }
}
现在将能够为这样的异常创建新的参数:
public class ExceptionAExceptionArgs : ExceptionArgs
{
//may add some properties if required here
}
并像这样捕获“新异常”:
try
{
//do something here...
}
catch (Exception<ExceptionAExceptionArgs> ex)
{
}
我会让你编写更少的代码来创建新的异常。
请注意:如果您想创建有一个基本异常类和几个子异常类的异常的层次结构,这种方法将不起作用。
您可以将异常类放在您想要的任何地方,以便可以访问,但为每个类创建单独的文件是一种好方法。