我制作了一个抛出异常的组件。我在考虑是否应该坚持标准throw new Exception
,或者是否应该创建特定的例外。
我还认为用户定义的异常在从 Remoting 或 WCF 引发异常时没有吸引力。如果我使用标准异常,调用者可以接收到异常,如果我做了一个用户定义的异常,调用者将无法接收到特定的异常,除非组件的程序集也部署到客户端;但是,如果从 Remoting 和 WCF 中捕获用户定义的异常并将其作为标准异常重新抛出,则客户端可以从用户定义的异常中接收异常,这反过来又破坏了用户定义的异常的目的。
什么时候添加用户定义的异常不是那么有用?
[编辑]
分享我的想法,我认为用户定义的异常是组件上的必须(至少一个),因此当您对自己的组件进行单元测试时,您不会收到误报。
这会产生误报:
[Test]
public void Tag_is_missing()
{
string message = "";
try
{
// Arrange
// this will fail on *nix systems
MyComponentHelper.ParseXml("C:\A.XML");
}
catch(Exception ex)
{
// Act
message = ex.InnerException.Message;
}
// Assert
// How can we be sure that the word "not found" error is from
// xml parsing or if from file loading? Doing Pokemon exception handling
// will lead to ambiguities
Assert.IsTrue(message.Contains("not found"));
}
如果您没有自己的异常,您的单元测试可能会收到误报,“未找到”字符串可能来自您的组件或组件的其他子系统。所以我的情况是什么时候应该创建用户定义的异常。
这不会产生误报:
[Test]
public void Tag_is_missing()
{
string message = "";
try
{
// Arrange
// this will fail on *nix systems
MyComponentHelper.ParseXml("C:\A.XML");
}
catch(XmlParsingException ex)
{
// Act
message = ex.InnerException.Message;
// Assert
// And now we are more sure that the error didn't come from
// program subsystem; in particular, file subsystem.
Assert.IsTrue(message.Contains("not found"));
}
}
剩下要思考的是何时应该创建非常具体的用户定义异常。现在,我将首先确定我的组件只有一个用户定义的异常,单元测试不应该产生误报。