簡體   English   中英

拋出異常后繼續流程

[英]Continue the flow after throwing exception

在我的用例中,我遍歷地圖並檢查列表中是否存在特定的鍵。 如果存在,則必須拖曳異常,否則繼續執行。

Map<A,B> myMap = new HashMap<A,B>();
//code to populate values in myMap
...
...
List<A> myList = new ArrayList<A>();
//code to populate values in myList
...
...
for(Map.Entry<A,B> eachElementInMap:myMap.entrySet()){
    if(myList.contains(eachElementInMap:myMap.getKey())){
        //throwing exception
        throw new MyCustomizedException("someString");
    }
}

//code continues
...
....

在上面的示例中,如果map(myMap)中有3個元素,其中list(myList)中存在1個鍵,我想拋出一個異常,並且應該繼續為其余兩個執行其他代碼行。 我是否使用錯誤的設計來實現這一目標? 任何幫助或建議,不勝感激! 謝謝

通常,一旦引發異常,就是說當前執行行應該終止而不是繼續。 如果您想繼續執行代碼,則可以推遲引發異常。

boolean fail = false;

for (Map.Entry<A,B> eachElementInMap:myMap.entrySet()) {
    if (myList.contains(eachElementInMap:myMap.getKey())) {
        // throw an exception later
        fail = true;
    }
}

if (fail) {
    throw new MyCustomizedException("someString");
}

您也可以從那里你它不同的位置創建一個異常對象。 在異常消息不僅是“ someString”,而且還需要從從被迭代的對象獲得的數據構造異常消息的情況下,這種慣用法很有用。

Optional<MyCustomizedException> exception = Optional.empty();

for (Map.Entry<A, B> eachElementInMap:myMap.entrySet()) {
    if (myList.contains(eachElementInMap.getKey())) {
        // Create an exception object that describes e.g., the missing key(s)
        // but do not throw it yet.
        if( exception.isPresent() ) {
            exception.get().addToDescription( /* Context-sensitive information */ );
        }
        else {
            exception = Optional.of(
                new MyCustomizedException( /* Context-sensitive information */));
        } 
    }
}

if( exception.isPresent() ) {
    throw exception.get();
}

如果異常中存儲的唯一數據是字符串,則可以通過在StringBuilder累積問題描述來達到等效的效果,但是對於需要將更多有趣的數據放入異常對象的情況,按需構建可能是值得的選擇考慮。

您可以將其分為兩個列表,失敗列表和成功列表。 並做到這一點。

這更清楚

failList = myMap.entrySet().stream().filter(p->myList.contains(p.getKey())).collect(Collectors.toList());
successList = myMap.entrySet().stream().filter(p->!myList.contains(p.getKey())).collect(Collectors.toList());

       failList.forEach(p -> {
            // fail code
        });
       successList .forEach(p -> {
            // success code
        });

為什么不使用if ... else而不是try catch? 錯誤只是意味着這是一個錯誤。 如果您擔心這會導致一些您不知道的錯誤。 您可以使用拋出錯誤。

無論如何,當您希望程序運行時,不應使用它

暫無
暫無

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

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