簡體   English   中英

即使在點擊 return 語句后循環繼續

[英]Loop continuing even after hitting return statement

我有以下方法,我想繼續檢查嵌套異常是否與 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 指出的那樣,您將遞歸和迭代混合在一起,並且都沒有正確執行。 一個(正確的)遞歸版本將是:

public boolean test(Throwable throwable) {
    if (throwable == null) {
        return false;
    } else if (throwable instanceof IndexOutOfBoundsException) {
        return true;
    } else {
        return test(throwable.getCause());
    }
} 

在我看來,遞歸版本比迭代版本更容易理解,但其他人可能不同意。

對於遞歸版本,存在足夠深的嵌套異常可能導致堆棧溢出的理論問題。 在實踐中實現這一點需要一些相當人為(即不切實際)的代碼,因此忽略這一點應該是安全的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM