Java finally Revisited
2015-06-03 17:39
447 查看
Interesting code snippet from reference [1]:
I changed a little and execute again:
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
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
相关文章推荐
- Java 内部类学习
- 标准版Eclipse4.4.2安装html/jsp插件
- Java内存区域
- 全方位的技术服务及相关技术解决方案(纯java解决方案)(转)
- 读SCJP认识一下Java(一)
- java synchronized 方法 对象 区别
- Java高级编程:深入剖析ThreadLocal
- struts2加载struts2常量顺序
- 5分钟将OSC Android源码从Eclipse项目转化为Android studio项目
- Java 实现zip格式的文件压缩与解压
- java Process的waitFor()
- Java中各种数据类型的存储-堆/栈
- Maven学习 之 使用m2eclipse创建web项目
- What to do about Eclipse's “No repository found containing: …” error messages?
- javamail发送hotmail邮件
- Java核心API -- 3(正则表达式)
- Java线程基础知识
- 13、Spring-shiro.xml
- JAVA单链表的实现-不带头结点但带有尾指针
- java中的subString详解及应用