try catch finally解惑
来源:互联网 发布:office2016软件下载 编辑:程序博客网 时间:2024/06/08 11:32
try catch finally解惑
Finally通常会配合try、catch使用,在try。。。catch没有退出的语句(return 或者是抛出异常导致退出try。。。catch)执行完try。。。catch语句后,再来执行finally;另外一种情况是在try。。。catch有退出的语句,在每一处的try或catch将要退出该方法之前,JVM都会保证先去调用finally的代码,这里所说的退出不单单是指return语句,try或catch中异常的抛出也会导致相应方法的退出(当然,前提是不被catch捕获以及不被finally跳转)。在执行finally代码时,如果finally代码本身没有退出的语句(return或抛出异常),finally执行完毕(除了finally中有return语句)后还会返回try或catch之前要退出的地方,由try或catch执行退出指令。
如
static intf4() {
try {
throw new Exception("try error ");
} catch (Exceptione) {
System.out.print("throw excetion ");
throw new RuntimeException("catch error ");
} finally {
System.out.print("f4");
Return 0;
}
}
结果:throw excetion f4 : 0
在通过外面的程序调用这个函数
try {
System.out.println(" : " +f4());
} catch (Exceptione) {
System.out.println(" : " +e.getMessage());
}
在上面程序中先抛出throw new Exception("try error"异常,同时被catch到然后执行
System.out.print("throw excetion");
当执行到throw new RuntimeException("catcherror"); 时,编译器知道这是退出的意识(还包括return 语句等),此时由于finally具有在try或catch将要退出(包括return 以及抛出异常)该方法之前,JVM都会保证先去调用finally的代码,此时执行finally中的代码
System.out.print("f4");
Return 0;
此时该函数f4()并没有向外抛射异常
同样的道理
static int f4() {
try {
throw new Exception("try error ");
} catch (Exceptione) {
System.out.print("throw excetion ");
return 1;
} finally{
System.out.print("f4");
return 0;
}
}
此时结果
throwexcetion f4 : 0
static int f4() {
try {
System.out.print("try ");
return 2;
} catch (Exceptione) {
System.out.print("throw excetion ");
return 1;
} finally{
System.out.print("f4");
return 0;
}
}
结果try f4 : 0
还有就是执行完try。。。catch(此时没有退出的语句)在执行完try。。。catch的语句后,再来执行finally如:
static int f4() {
try {
System.out.print("try ");
} catch (Exceptione) {
System.out.print("throw excetion ");
} finally{
System.out.print("f4");
return 0;
}
}
结果try f4 : 0
- try catch finally解惑
- Java解惑之try catch finally
- Java解惑之try catch finally
- Java解惑之try catch finally
- Java解惑之try catch finally
- Java解惑之try catch finally
- java解惑之try catch finally
- java 异常 Exception 相关 try catch finally 解惑
- 关于try finally解惑
- try..catch..finally
- try-catch-finally
- Try-catch-finally机制
- 关于try-catch-finally
- C# try catch finally
- try...catch...finally
- try catch finally用法
- Try ---Catch----Finally
- try...catch... finally
- 读取配置文件 方式二(推荐):
- 旅行售货员问题
- 代码杂记(六)
- Hibernate中一级缓存、二级缓存及查询缓存的技术性总结
- start blogging
- try catch finally解惑
- 读书记录
- OpenLayers3+OpenStreetMap初探
- 复数模板类1
- Mac和Ubuntu下安装Erlang
- Hibernate的session.flush做了什么呢【1】
- Fragment不同操作的生命周期
- 电影记录
- stm32F4的NVIC和中断