即使点击返回语句,循环仍继续

问题描述

我有以下方法,希望继续检查嵌套异常是否与indexoutofboundsexception匹配,除非嵌套异常与上一个异常相同。

在我的测试中,第一个例外似乎做对了 类型为NullPointerException,因此继续进行下一个。如预期的那样,下一个异常是indexoutofboundsexception

发生这种情况时,我想返回true,我希望这能使我脱离循环。 我确实在“回归真相”的地方发生了预期的事情。但是之后,循环继续进行。

我想念的是什么。返回true后如何继续进行?

public boolean test(Throwable throwable) {

    do {
        if(throwable instanceof indexoutofboundsexception) {
            return true; // I do land here thus expecting to get out of loop and this method.
        }
        this.test(throwable.getCause());
    } while (throwable.getCause() != throwable);

    return false;
}

针对它的模拟嵌套异常的测试。

@Test
void testWithnestedException() {
    NullPointerException nullPointerException = new NullPointerException();
    indexoutofboundsexception indexoutofboundsexception = new indexoutofboundsexception();
    Throwable nestedException = nullPointerException.initCause(indexoutofboundsexception);
    assertTrue(someClass.test(nestedException));
}

解决方法

您正在将递归与循环混合在一起。在这里,一个简单的循环更新正在测试的异常应该可以解决问题:

public boolean test(Throwable throwable) {
    Throwable t = throwable;
    do {
        if (throwable instanceof IndexOutOfBoundsException) {
            return true;
        }
        t = t.getCause();
    } while (t.getCause() != t);

    return false;
}
,

您正在通过此调用创建递归,并且请勿使用此调用的返回代码。

this.test(throwable.getCause());

我认为您想这样做:

throwable = throwable.getCause();
,

正如@Mureinik指出的那样,您正在混合递归和迭代,但未正确执行。 (正确的)递归版本为:

npx create-react-app my-app

我认为,递归版本比迭代版本更易于理解,但其他版本可能会不同意。

使用递归版本时,存在一个理论上的问题,即深度嵌套过多的异常可能导致堆栈溢出。要在实践中实现这一点,将需要一些相当人为的(即,不现实的)代码,因此可以无视此点。