您的位置:首页 > 编程语言 > Java开发

Java finally Revisited

2015-06-03 17:39 447 查看
Interesting code snippet from reference [1]:

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

public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
Output:

try
catch
finally
return in finally


I changed a little and execute again:

public class Test {

public static void main(String args[]) {
System.out.println(Test.test());
}

public static String test() {
try {
System.out.println("try");
return "return normal";
} catch (Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}

}
Output:

try
finally
return in finally


So, just like reference [1] another answer:

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

Reference:
[1] http://stackoverflow.com/questions/15225819/try-catch-finally-return-clarification-in-java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: