Java最终阻止并在方法级别抛出异常

gig*_*dot 10 java exception-handling

在中readFileMethod1,IOException在将其抛出到方法级别之前显式捕获,以确保finally执行该块.但是,是否需要捕获异常?如果我删除catch块,如图所示readFileMethod2,finally块也会被执行吗?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*hes 8

finally仍然被执行,不管你是否赶上IOException异常.如果你的所有catch块都是重新抛出,那么这里没有必要.