Exception 有没有可能使这个图案更干燥?

Exception 有没有可能使这个图案更干燥?,exception,language-agnostic,control-flow,Exception,Language Agnostic,Control Flow,我已经遇到过几次了: try { if (condition()) { return simpleFunction(with, some, args); } else { return complexFunction(with, other, args); } catch (something) { // Exception thrown from condition() return complexFunction(with, other, args); }

我已经遇到过几次了:

try {
  if (condition()) {
    return simpleFunction(with, some, args);
  } else {
    return complexFunction(with, other, args);
  }
catch (something) {
  // Exception thrown from condition()
  return complexFunction(with, other, args);
}
是否有任何方法(以任何语言)避免重复调用complexFunction?理想情况下,不要模糊代码的意图?

如果是c#,您可以

    try
    {
        if (condition()) {
            return simpleFunction(with, some, args);
        }
    }
    catch
    {
        // Swallow and move on to complex function
    }

    return complexFunction(with, other, args);
已更新以使条件异常继续在堆栈上运行

if (condition()) {
    try
    {
        return simpleFunction(with, some, args);
    }
    catch
    {
        // Swallow and move on to complex function
    }
}
return complexFunction(with, other, args);
如果c#,你可以

    try
    {
        if (condition()) {
            return simpleFunction(with, some, args);
        }
    }
    catch
    {
        // Swallow and move on to complex function
    }

    return complexFunction(with, other, args);
已更新以使条件异常继续在堆栈上运行

if (condition()) {
    try
    {
        return simpleFunction(with, some, args);
    }
    catch
    {
        // Swallow and move on to complex function
    }
}
return complexFunction(with, other, args);

如果
condition()
失败,则引发异常

try
{
  if (condition())
  {
    return simpleFunction();
  }
  throw conditionException();
}
catch(conditionException ce)
{
  return complexFunction();
}

正如有人善意地指出的,这不是编写代码的方式。然而,它确实解决了这个问题——在某种程度上,它似乎符合问题中“模式”的意图,即如果条件抛出异常或返回false,则认为它失败了。

如果
条件()
失败,则抛出异常

try
{
  if (condition())
  {
    return simpleFunction();
  }
  throw conditionException();
}
catch(conditionException ce)
{
  return complexFunction();
}

正如有人善意地指出的,这不是编写代码的方式。然而,它确实解决了这个问题——在某种程度上,它似乎与问题中“模式”的意图相匹配,即如果条件抛出异常或返回false,则认为它失败了。

这并没有捕获从条件抛出的异常,实际上只捕获从simpleFunction()抛出的异常,我以为您正在捕获simplefunction()。我会把它更新的很好!我知道我在问题中没有提到它,我也没有在实践中遇到过它,但是你能不能更新它,使它能够处理从condition()引发的不同类型的异常,但是这个异常应该继续在堆栈中传递?我已经按照要求进行了更新
condition()
现在将被捕获并按请求向上发送堆栈hold up。。。我本来就是这样的。。。?(正如注释1中指出的那样。很抱歉,我可能会误解这并没有捕获从条件抛出的异常,只是从simpleFunction()中抛出的异常。事实上,我假设您正在捕获simpleFunction())。我会更新它的!我知道我在问题中没有提到它,而且我在实践中也没有遇到过它,但是你能更新它以便它能够处理从condition()引发的不同类型的异常吗,但是这个异常应该继续被忽略?我已经按照要求进行了更新。
condition()
现在将被捕获并按请求发送堆栈暂停…这就是我最初使用它的方式…?(如评论1中所指出的。很抱歉,我可能会误解。很酷!我没有想到那一个。很酷!我没有想到那一个。