如何在Java中实现`finally` for error case

Sna*_*akE 1 java exception-handling

如果发生任何错误,我需要触发一些代码.基本上我需要一个finally只在异常的情况下执行的块.我会这样实现它:

HttpURLConnection post(URL url, byte[] body) throws IOException {
    HttpURLConnection connection = url.openConnection();
    try {
        OutputStream out = connection.getOutputStream();
        try {
            out.write(body);
        } finally {
            out.close();
        }
        return connection;
    } catch (Throwable t) {
        connection.disconnect();
        throw t;
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来很好 - 除了它不会编译:我的函数不能抛出Throwable.

我可以重写:

    } catch (RuntimeException e) {
        connection.disconnect();
        throw e;
    } catch (IOException e) {
        connection.disconnect();
        throw e;
    }
Run Code Online (Sandbox Code Playgroud)

但即便如此,我仍然是a)错过所有错误,并且b)必须在我改变实现时抛出不同类型的异常时修复此代码.

是否有可能一般地处理这个问题?

Ano*_*on. 11

您可以使用finally块,并添加一个标志以指示成功.

bool success = false;
try {
    //your code
    success = true;
    return retVal;
} finally {
    if (!success) {
        //clean up
    }
}
Run Code Online (Sandbox Code Playgroud)