如果发生任何异常,如何在try块中重试特定的代码段?

joh*_*ohn 0 java try-catch

我需要使用JSOUP解析来自URL的HTML表格,现在一切正常.现在我想添加一个重试机制,如果我看到任何异常.以下是我的代码 -

public void collectMetrics() {
    try {
        URL url = new URL("some_url");
        Document doc = Jsoup.parse(url, 9000);
        for (Map.Entry<String, String> entry : mappings.entrySet()) {
            calculateDiskFree(doc, entry.getValue(), entry.getKey());
        }
        // if it comes here, then it means everything is done successfully 
        // so no retry has to happen now
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果catch块中发生任何异常,我想重试我在try块中执行的所有操作n多次.有可能吗?

khe*_*ood 5

你可以把它放在一个循环中.

boolean successful = false;
while (!successful) {
    try {
        URL url = new URL("some_url");
        Document doc = Jsoup.parse(url, 9000);
        for (Map.Entry<String, String> entry : mappings.entrySet()) {
            calculateDiskFree(doc, entry.getValue(), entry.getKey());
        }
        successful = true;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是你可能想要考虑如果它一直失败会发生什么.如果您只想重试某些特定次数,则可以使用for循环.

for (int retries = 0; retries < 3; ++retries) {
    try {
        URL url = new URL("some_url");
        Document doc = Jsoup.parse(url, 9000);
        for (Map.Entry<String, String> entry : mappings.entrySet()) {
            calculateDiskFree(doc, entry.getValue(), entry.getKey());
        }
        break;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)