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

java return 和throw

2016-04-22 00:00 225 查看
摘要: java return 和throw

return 在finally之外:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class TestThrow {
public static void main(String[] args) {
TestThrow t=new TestThrow();
try{
System.out.println(t.testTry());
}catch(Exception e){
System.out.println("this is exception in main");
}finally {
System.out.println("this is finished in main");
}

}
public int testTry() throws Exception{
FileInputStream fi=null;
int flag = 0;

try{
fi=new FileInputStream("");

}catch(FileNotFoundException fnfe){
System.out.println("this is FileNotFoundException");
flag = 2;
throw new FileNotFoundException();
//return 2;
}catch(SecurityException se){
System.out.println("this is SecurityException");
flag = 1;
//return 1;
}catch(Exception se){
System.out.println("this is Exception");
flag = 3;
throw new Exception();
}finally{
System.out.println("this is finally in test");
flag = 4;
//return 4;
}

System.out.println("this is end!!");
return flag;
}
}


编译:

javac TestThrow.java

执行:

this is FileNotFoundException
this is finally in test
this is exception in main
this is finished in main

结论:

finally的意思是无论try块中有没有发生异常finally块中的代码都会执行。return flag;如果放在finally外,那么try中异常后,catch住然后throw e;方法就中止执行了,则不会执行return flag;

return 在finally之内:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class TestThrow {
public static void main(String[] args) {
TestThrow t=new TestThrow();
try{
System.out.println(t.testTry());
}catch(Exception e){
System.out.println("this is exception in main");
}finally {
System.out.println("this is finished in main");
}

}
public int testTry() throws Exception{
FileInputStream fi=null;
int flag = 0;

try{
fi=new FileInputStream("");

}catch(FileNotFoundException fnfe){
System.out.println("this is FileNotFoundException");
flag = 2;
throw new FileNotFoundException();
//return 2;
}catch(SecurityException se){
System.out.println("this is SecurityException");
flag = 1;
return 1;
}catch(Exception se){
System.out.println("this is Exception");
flag = 3;
//throw new Exception();
return 3;
}finally{
System.out.println("this is finally in test");
flag = 4;
return 4;
}

//System.out.println("this is end!!");
//return flag;
}
}

编译:

javac TestThrow.java

执行:

this is FileNotFoundException
this is finally in test
4
this is finished in main

结论:

return flag;放在finally内,try中异常后,catch住然后throw e;方法中止执行抛出异常前会先执行finally块中的语句,而finally中又使方法正常返回。所以就导致了异常没被抛出。

另外,代码修改为如下时,打印值也相同。

//throw new FileNotFoundException();
return 2;


注释:

当finally中有return的时候,异常是被存入了栈中,但是最终未被抛给调用者。

总结:
1、不管有没有出现异常,finally块中代码都会执行;
2、当try和catch中有return时,finally仍然会执行;
3、finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,管finally中的代码怎么样,返回的值都不会改变,扔然是之前保存的值),所以函数返回值是在finally执行前确定的;
4、finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值。

参考:
http://bbs.csdn.net/topics/390815821
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: