Try-catch-finally in java

若如初见. 提交于 2019-11-30 02:58:20

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.

stacker

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

bljsajdajdlkasjd

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();
    }
}

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."

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.

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.

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.

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.

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