try/catch block return with finally clause in java [duplicate]

心已入冬 提交于 2019-12-02 08:01:59

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.

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