假设有这样的设置:
public class MyClass
{
public void DoSomething(string Data)
{
//if (String.IsNullOrWhiteSpace(Data))
//throw new NullReferenceException();
//Do something with Data and let it throw??
}
}
public class EntryPointClass
{
public void DoIt(string Data)
{
var logicClass = new MyClass();
try
{
logicClass.DoSomething(Data);
}
catch(Exception ex)
{
}
}
}
在 DoSomething 中,我可以检测到问题并引发异常。在测试 EntryPointClass 时,我可以测试预期结果或测试 catch 中发生的情况。
为什么抛出异常比等待异常发生更好?不管怎样,我们已经抓住了它!
你两者都做:
public void DoSomething(string Data)
{
if (String.IsNullOrWhiteSpace(Data))
//throw new NullReferenceException();
throw new ArgumentException("Data");
//Do something with Data and let it throw??
}
目的是尽早抛出并提供具体信息。
抛出这里的直接原因是与DoSomething()
被打破。发出信号,不要等待“DoSomething()”继续执行并破坏其他合约。
快失败,早失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)