关于Java中异常捕获的问题

时间:2010-12-28 17:34:46

标签: 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的建议,我将不胜感激,提前感谢。

6 个答案:

答案 0 :(得分:3)

我认为你可以在这里找到答案:Validating URL in Java

答案 1 :(得分:2)

以下代码应该做你喜欢的。基本上,在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.

答案 2 :(得分:1)

一般提示:不要只写“捕获”。始终指定要捕获的异常类型(最好是您自己的自定义异常类型),以便您知道代码完全符合您的意思。否则,如你所说,catch语句可能会捕获一些你不想发生的其他类型的异常,实际上应该向上抛出。

答案 3 :(得分:0)

跟踪变量和循环中的尝试次数,直到成功或最大尝试次数(我选择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

答案 4 :(得分:0)

您应该单独捕获相应的异常,并根据捕获的异常执行不同的错误处理逻辑。这被认为是最好的方法,因为它将错误条件与正常逻辑分开,你可以用不同的方式处理不同的错误。

在正常的逻辑流程中,它被认为比if else语句更好。

答案 5 :(得分:0)

尝试这样的事情:

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;
  }

}

*编辑从上一个答案中提取的其他代码:Validating URL in Java

相关问题