天天看點

return和finally使用

在java中finally一般出現在try{}結構中,用于存放try結構中一定要執行的語句,如

  String s = "1";

  try{

   s = "2";

   System.out.println(s);

   if(s=="2")

    throw new Exception("h");

  }catch(Exception e){

   s = "3";   

   System.out.println(s);

  }finally{

   s = "4";

   System.out.println(s);

  } 

  s = "5";

  System.out.println(s);

輸出的結果是2,3,4,5    (這裡的逗号隻用于顯示)。上述語句非常清楚,但是在上述結構中加上return,就變得有些複雜了,如

  String s = "1";

  try{

   s = "2";

   System.out.println(s);

   return;

  }catch(Exception e){

   s = "3";   

   System.out.println(s);

  }finally{

   s = "4";

   System.out.println(s);

  } 

  s = "5";

  System.out.println(s);

輸出的結果是2,4

也就是說在try結構中,雖然使用了return語句強制函數傳回,不再往下執行,但實作上finally中的還是執行了。但除了finally外的其它語句不再被執行。

return和finally使用