问题描述
让我们说有设置是这样的:
Lets say there is setup like this:
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我可以测试预期结果或测试在捕获发生的东西。
In DoSomething I can detect a problem and throw an exception. In testing EntryPointClass I can test the expected outcome or test that something in happened in the catch.
为什么它更好地抛出一个异常,而不是只是等待一次发生? !不管怎样,我们已经把它抓住。
Why is it better to throw an exception rather than just wait for one to happen? Either way we've caught it!
推荐答案
您一举两得:
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的()进行,打破其他合同。
The aim is to throw early and provide specific information.
The direct reason to throw here is that the contract with DoSomething()
is broken. Signal it, don't wait for `DoSomething() to carry on and break other contracts.
快速失败,失败早。
这篇关于最好以检测异常并把他们或只是让运行时扔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!