Java eventually blocks and throws exceptions at the method level

In readfilemethod1, IOException is explicitly captured before it is thrown at the method level to ensure that the finally block is executed However, do you need to catch exceptions? If I delete the catch block in readfilemethod2, will the finally block also be executed?

private void readFileMethod1() throws IOException {
    try {
        // do some IO stuff
    } catch (IOException ex) {
        throw ex;
    } finally {
        // release resources
    }
}

private void readFileMethod2() throws IOException {
    try {
        // do some IO stuff
    } finally {
        // release resources
    }
}

Solution

Finally, it will still be executed, whether you catch IOException or not If all catch blocks are re - thrown, then this is not necessary

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>