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

烂漫一生 提交于 2019-12-20 06:48:09

问题


Given the following try/catch block in java:

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

and according to this post: "Does finally always execute in Java?" I can see that the program's output will be 'This is the finally block'. However, I can't figure out how that would be possible since the print statement is preceded by a return...

I suspect that this behaviour has something to do with threading, however I am not certain. Please enlighten me. Thank you.


回答1:


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




回答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




回答3:


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.



来源:https://stackoverflow.com/questions/19899155/try-catch-block-return-with-finally-clause-in-java

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