簡體   English   中英

關於Java中異常捕獲的問題

[英]A question about exception catching in Java

我有一個實例方法,在其中,我做了一個簡單的網頁解析:

public void doOperation(final AuthorAccess authorAccess, ArgumentsMap arguments) throws  IllegalArgumentException,AuthorOperationException
{

    final String server = "chiexist1.worldbook.com";
    final String port = "8080";
    try {

             docBuilder = docFactory.newDocumentBuilder();
             doc = docBuilder.parse("http://" + server + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
        ...}
       catch{}
  }

因為目前我在字符串中對服務器地址進行硬編碼,所以可能存在服務器名稱不正確的情況,因此在這種情況下,我希望它自動將服務器URL字符串更改為“localhost”。

我認為if-else語句可能會起作用,但我不太確定如何確定布爾變量以檢測此解析是否失敗。 我還想把它放在catch語句中,但是其他語句也會拋出異常呢?

我還檢查了DocumentBuilder的API,parse()方法總是返回Document Type但不返回boolean。 所以,如果有人能在這里給我一些關於如何檢測被委屈的URL然后改為解析localhost的建議,我將不勝感激,提前感謝。

我想在這里你可以找到答案: 用Java驗證URL

以下代碼應該做你喜歡的。 基本上,在catch只需從localhost構建另一個doc。

final String server = "chiexist1.worldbook.com";
final String port = "8080";
docBuilder = docFactory.newDocumentBuilder();
doc = null;
try {
    doc = docBuilder.parse("http://" + server + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
} catch{
    try{ 
        doc = docBuilder.parse("http://" + "localhost" + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
    } catch {
        // now we have an error we can't recover from
    }
}
...  // I meant to do this before.

一般提示:不要只寫“catch”。 始終指定要捕獲的異常類型(最好是您自己的自定義異常類型),以便您知道代碼完全符合您的意思。 否則,如你所說,catch語句可能會捕獲一些你不想發生的其他類型的異常,實際應該向上拋出。

跟蹤變量和循環中的嘗試次數,直到成功或最大嘗試次數(我選擇5)通過:

String server = "chiexist1.worldbook.com";
final String port = "8080";
int attempts = 0;
final int MAX_ATTEMPTS = 5;
boolean success = false;
docBuilder = docFactory.newDocumentBuilder();
while (!success && attempts < MAX_ATTEMPTS) {
    try {
        doc = docBuilder.parse("http://" + server + ":" + port + "/exist/webdav/db/portfolio/config/products.xml");
        success = true;
    } catch (IOException e) {
        if (++attempts < MAX_ATTEMPTS) {
            System.err.println("Attempt to connect to " + server + ":" + port + " failed. Retrying" + (attempts == 1 ? ", but connecting to localhost:" + port + " this time" : "") + ".");
            server = "localhost";
        } else {
            System.err.println("Attempt to connect to " + server + ":" + port + " failed. Giving up after " + attempts + " failed attempts.");
        }
    } 
}
if (!success) {
    // Tidy up and exit
}
// Do stuff

您應該單獨捕獲相應的異常,並根據捕獲的異常執行不同的錯誤處理邏輯。 這被認為是最好的方法,因為它將錯誤條件與正常邏輯分開,並且您可以以不同的方式處理不同的錯誤。

它被認為比正常邏輯流程中的else語句更好。

嘗試這樣的事情:

static String hostname = "hostname";
static{
   if(doesHostExist(hostName)==false){
     hostname="localhost";
   }
}

private static boolean doesHostExist(String host){
  try {
    URL url = new URL("http://" + host);
    URLConnection conn = url.openConnection();
    conn.connect();
    return true;
  } catch (MalformedURLException e) {
    return false;
  } catch (IOException e) {
    return false;
  }

}

*編輯從上一個答案解除的其他代碼: 在Java中驗證URL

暫無
暫無

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

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