Try-catch-finally in java

怎甘沉沦 提交于 2019-12-03 18:57:04

问题


In Java, will the finally block not get executed if we insert a return statement inside the try block of a try-catch-finally ?


回答1:


The only time a finally block will not be executed is when you call exit() before finally is reached. The exit() call will shutdown the JVM, so no subsequent line of code will be run.

EDIT: This is not entirely correct. See the comments below for additional information.




回答2:


The finally block will always execute no matter if you return, or an exception is thrown within the try block.

See also section 14.19.2 Execution of try-catch-finally of the Java Language Specification




回答3:


The finally block gets executed in all these cases. The point of executing finally block at the end is to allow you to release all the acquired resources.

Below is an example that shows how it works.

public class Hello {

    public static void hello(){
        try{
            System.out.println("hi");
            return;
            }catch(RuntimeException e){
        }finally{
            System.out.println("finally");

        }

    }

    public static void main(String[] args){
        hello();
    }
}



回答4:


It gets executed even if you return inside the try block. I put one return statement inside try as well as one inside finally and the value returned was from finally, not from try.

public class HelloWorld{
   public static void main(String args[]){
      System.out.println(printSomething());
   }

   public static String printSomething(){
      try{
          return "tried";
      } finally{
          return "finally";
      }
   }
}

The output I got was "finally."




回答5:


According to the official explanation:

Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. 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.

I think it's a good idea that we should refer to the official website before we post an answer here.




回答6:


When ever a method tries to return to the caller, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.




回答7:


If your finally block has a return, it will override any return in a try-catch block.Because of this "feature" a good practice is that finally block should never throw an exception or have a return statement.




回答8:


If you call System.exit() as someone else said, it will not be executed, but I believe it will also not be executed if there is an exception in the except block.



来源:https://stackoverflow.com/questions/7143788/try-catch-finally-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!