我已经在各种项目上遇到了这个问题几次,我想知道是否有比通常最终使用的解决方案更好的解决方案。假设我们有一系列需要执行的方法,并且我们想知道某个方法中是否出现了问题,并且可以正常打破(可能会撤销之前的更改...),但我通常会这样做以下(伪C#,因为它是我最熟悉的):错误处理的设计模式
private bool SomeMethod()
{
bool success = true;
string errorMessage = null;
success = TestPartA(ref errorMessage);
if (success)
{
success = TestPartB(ref errorMessage);
}
if (success)
{
success = TestPartC(ref errorMessage);
}
if (success)
{
success = TestPartD(ref errorMessage);
}
//... some further tests: display the error message somehow, then:
return success;
}
private bool TestPartA(ref string errorMessage)
{
// Do some testing...
if (somethingBadHappens)
{
errorMessage = "The error that happens";
return false;
}
return true;
}
我只是想知道(这是我的问题),如果有对于这种事情的应对更好的方法。我似乎最终写了很多if
声明,看起来应该是很冷静的。
我已经被建议循环使用一组委托函数,但是我担心会过度设计解决方案,除非有一个干净的方法来做到这一点。
如果这些确实是错误,那么你应该抛出异常。 – Polyfun