簡體   English   中英

拋出異常但不停止程序的最佳方法是什么?

[英]What is the best way to throw an Exception but not stop the program?

請在下面找到我需要的示例。 確實,我不想關閉整個過程,因為即使它拋出異常,它也可以繼續。

環形

// set a lot of variables and execute some methods
for (int i = 0, i < items.length; i++) {
     // blablabla
     myMethod()
     // blablabla2
}
// some code here also

我的方法()

// blabla
if (!found)
     throw new EndCurrentProcessException()
// blabla

結束當前進程異常

public void EndCurrentProcessException() {
     ??? What I'm supposed to put here to stop the loop iteration ???
}

也許使用throw new不是好方法。

我希望很清楚,如果不是,請隨時向我詢問更多信息。

不要拋出異常。 以您認為合適的方式處理方法失敗。

在您的示例中,修改myMethod()方法以在成功時返回布爾值true ,否則返回false

環形:

// set a lot of variables and execute some methods
for (int i = 0, i < items.length; i++) {
   // blablabla
   if (!myMethod()) {
       // Skip this particular ITEM...
       continue;
       // Or whatever you want.
   }
   // blablabla2
}

我的方法():

public boolean myMethod() {
    // ... Method code ...
    if (!found) {
        return false;
    }
    // ... Possibly more Method code ...
    return true;
}

嘗試使用 try-catch 語句。

for (int i = 0, i < items.length; i++) {
    // blablabla
    try {
        myMethod();
    } catch(EndCurrentProcessException e){
        // do something or continue;
        continue;
    }
    // blablabla2
 }
 // some code here also

暫無
暫無

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

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