JAva returnとthrow
3986 ワード
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 FileNotFoundExceptionthis is finally in testthis is exception in mainthis 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 FileNotFoundExceptionthis is finally in test4this 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