java Exception return 值的讨论

今天来分析下java 中Exception的处理方式,我们都知道,它执行的顺序如下:

[b]1. try:检查是否有异常发生;
2. 如果有,则由catch来捕获;
3. 不管是否有异常发生,都会进入到finally里执行。[/b]

先记住下面的结论:

[b]1. throw 后面的代码是不会执行的。
2. 不管是否有异常,都会执行finally。
3. 不管有多少个return, 只会执行finally里的return。[/b]

例1.

public class Demo {
public static int doexception(){
try{
return 1;
}catch(Exception e){
System.out.println("catch exception");
return 0;
}finally{
System.out.println("finally ....");
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}
}


输出结果:

finally ....
return value:1


例2.


public class Demo {
public static int doexception(){
try{
throw new Exception("aaa");
}catch(Exception e){
System.out.println("catch exception");
return 0;
}finally{
System.out.println("finally ....");
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}
}


输出结果:

catch exception
finally ....
return value:0


例3.


public class Demo {
public static int doexception(){
try{
throw new Exception("aaa");
}catch(Exception e){
System.out.println("catch exception");
return 0;
}finally{
System.out.println("finally ....");
return 1;
}
}
public static void main(String args[]){
System.out.println("return value:"+doexception());
}
}


输出结果:

catch exception
finally ....
return value:1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值