简体   繁体   English

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

[英]Java finally block and throws exception at method level

In readFileMethod1 , an IOException is explicitly catched before throwing it at the method level to ensure that the finally block is executed.readFileMethod1中, IOException在将其抛出到方法级别之前被显式捕获,以确保执行finally块。 However, is it neccessary to catch the exception?但是,是否有必要捕获异常? If I remove the catch block, shown in readFileMethod2 , does the finally block get executed as well?如果我删除了readFileMethod2中显示的 catch 块, 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
    }
}

The finally still gets executed, regardless of whether you catch the IOException. finally仍然会被执行,不管你是否捕获了 IOException。 If all your catch block does is rethrow, then it is not necessary here.如果你的 catch 块所做的只是重新抛出,那么这里就没有必要了。

No, it's completely unnecessary to catch an exception if you're not going to do anything other than throw it.不,如果您除了抛出异常之外什么都不做,那么捕获异常是完全没有必要的。

And yes, the finally block will still be executed.是的,finally 块仍然会被执行。

No, it isn't necessary to catch the exception unless you can't rethrow it in your method.不,没有必要捕获异常,除非您不能在您的方法中重新抛出它。 In the code you posted the readFileMethod2 is the correct option to follow.在您发布的代码中, readFileMethod2 是要遵循的正确选项。

the finally always get executed in try catch context... for more info check http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html finally 总是在 try catch 上下文中执行...有关更多信息,请检查http://download.oracle.com/javase/tutorial/essential/exceptions/finally.ZFC35FDC70D5FC69D269883A822C7A53

finally is executed always irrespective of whether an exception is thrown or not.无论是否抛出异常,最终都会执行。 Only if the JVM is shut down while executing the try block or catch block, then the finally clause will not be executed.只有在执行 try 块或 catch 块时 JVM 被关闭,才不会执行 finally 子句。 Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.同样,如果执行 try 或 catch 代码的线程被中断或杀死,即使应用程序作为一个整体继续运行,finally 块也可能不会执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM