try/catch block return with finally clause in java

This question already has an answer here:

  • Does finally always execute in Java? 50 answers

  • finally is executed before return statement. As java rule finally will always be executed except in case when JVM crashes or System.exit() is called.

    Java Language Specification clearly mentions the execution of finally in different conditions:

    http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2


    return statement has no effect on the execution of finally block. The only way a finally block isn't executed is in case if JVM crashes/exits before executing finally block. Check this Link for more. So, if your code is replaced by

    try{
      System.exit(0);
    }
    catch(SomeException e){
      System.out.println(e);
    }
    finally{
      System.out.println("This is the finally block");
    }
    

    The finally block won't execute


    Juned is correct. I also wanted to caution about throwing exceptions from finally blocks, they will mast other exceptions that happen. For example (somewhat silly example, but it makes the point):

    boolean ok = false;
    try {
       // code that might throw a SQLException
       ok = true;
       return;
    }
    catch (SQLException e) {
       log.error(e);
       throw e;
    }
    finally {
       if (!ok) {
          throw new RuntimeException("Not ok");
       }
    }
    

    In this case, even when an SQLException is caught and re-thrown, the finally throws a RuntimeException here and it it will "mask" or override the SQLException. The caller will receive the RuntimeException rather then the SQLException.

    链接地址: http://www.djcxy.com/p/73708.html

    上一篇: 这将最终阻止执行?

    下一篇: 在java中尝试/ catch块返回与finally子句