簡體   English   中英

處理異常后如何恢復代碼操作?

[英]how to resume code operation after handle exception?

問:處理異常后如何恢復代碼操作? 我現在使用try and catch。

Try
{
    Process url and render the text and save contents to text file.
}Catch(Exception ex)
}

有些網址已損壞,那么如何跳過損壞的網址並繼續使用其他網址?

取決於您如何遍歷URL。 例如:

for (URL url: urllist) {
  try {
    // Process **one** url
  } catch (Exception ex) {
    // handle the exception
  }
}

即使某些處理引發異常,這也會處理列表中的所有url。

就是這樣-不執行任何操作(除了可能記錄警告),然后代碼執行將繼續。 例如:

for (String url : urls) {
    try {
        // parse, open, save, etc.
    } catch (Exception ex) {
        log.warn("Problem loading URL " + url, ex);
    }
}

嘗試這個:

for (url : allUrls) {
   try {
       Process url and render the text and save contents to text file.
   } catch(Exception ex) {
      ...
      continue;
   }
}

創建兩個這樣的方法:

public void processAllURLs(final List<String> urls){
    for(String url: urls){
        processURL(url);
    }
}

public void processURL(final String url){
    try {
        // Attempt to process the URL
    } catch (Exception ex) {
        // Log or ignore
    }
}

此偽代碼中存在邏輯錯誤。

這樣想吧。 您的“過程網址”是一個循環,是嗎? 當發現異常時,它退出流程循環,到達catch塊,然后到達算法結尾。

您需要將整個try catch塊嵌套在流程循環中。 這樣,當它遇到異常時,它將返回到循環的開頭,而不是返回到程序結尾。

暫無
暫無

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

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