如果finally中有return 则直接返回结果。
一、
//先执行1,int result=a+b+j; 遇到return,即 return result; 则执行finally, 之后再次执行return result完成调用。
输出为:
finally语句块 语句块
和是: 43
public class Demo1 {
public int add(int a,int b){
int j=0;
try{
int result=a+b+j; //----1
return result; //---2
}catch(Exception e){
System.out.println("catch 语句块");
}finally{
System.out.println("finally语句块 语句块"); //---3
}
return 0; //--4
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo1 d=new Demo1();
System.out.println("和是: "+d.add(9, 34));
}
}
二、
首先执行int result=a+b+j;,之后遇到 return result;,则需要执行finally,因finally中有return 0,则直接返回
输出为:finally语句块 语句块
和是: 0
public class Demo1 {
public int add(int a,int b){
int j=0;
try{
int result=a+b+j;
return result;
}catch(Exception e){
System.out.println("catch 语句块");
}finally{
System.out.println("finally语句块 语句块");
return 0;
}
//return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo1 d=new Demo1();
System.out.println("和是: "+d.add(9, 34));
}
}
三、
输出;finally语句块 语句块
和是: 43
package zhongxin;
public class Demo1 {
public int add(int a,int b){
int j=0;
try{
int result=a+b+j;
return result;
}catch(Exception e){
System.out.println("catch 语句块");
}finally{
System.out.println("finally语句块 语句块");
//return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo1 d=new Demo1();
System.out.println("和是: "+d.add(9, 34));
}
}
1507

被折叠的 条评论
为什么被折叠?



