public class JVMTest {
public static void main(String[] args){
System.out.println("aa:" + aa());
}
public static int aa(){
int a = 1;
int b = 10;
try{
System.out.println("abc");
return a;
}finally{
a = 2;
System.out.println("a: "+ a);
}
}
}
運(yùn)行結(jié)果為:
abc
a: 2
aa:1
由此可知:在try語句中,在執(zhí)行return語句時(shí),要返回的結(jié)果已經(jīng)準(zhǔn)備好了,就在此時(shí),程序轉(zhuǎn)到finally執(zhí)行了。
在轉(zhuǎn)去之前,try中先把要返回的結(jié)果存放到不同于a的局部變量中去,執(zhí)行完finally之后,在從中取出返回結(jié)果,
因此,即使finally中對變量a進(jìn)行了改變,但是不會(huì)影響返回結(jié)果。
但是,如果在finally子句中最后添加上return a會(huì)怎樣呢?
執(zhí)行結(jié)果如下:
Compiling 1 source file to E:\sun\InsideJVM\build\classes
E:\sun\InsideJVM\src\JVMTest.java:37: warning: finally clause cannot complete normally
}
1 warning
compile-single:
run-single:
abc
a: 2
aa:2
測試1:
public static int test1()
{
int i = 1;
try
{
return ++i;
}
finally
{
++i;
Console.WriteLine("finally:" + i);
}
}
static void Main(string[] args)
{
Console.WriteLine("Main:" + test1());
}
結(jié)果:
finally:3
Main:2
測試2:
public static int test2()
{
int i = 1;
try
{
throw new Exception();
}
catch
{
return ++i;
}
finally
{
++i;
Console.WriteLine("finally:" + i);
}
}
static void Main(string[] args)
{
Console.WriteLine("Main:" + test2());
}
結(jié)果:
finally:3
Main:2
測試3:
public static int test3()
{
try{}
finally
{
return 1;
}
}
結(jié)果:
編譯錯(cuò)誤,控制不能離開 finally 子句主體。
結(jié)論:
1.不管出沒出現(xiàn)異常,finally塊中的語句都會(huì)執(zhí)行;
2.當(dāng)try或catch塊中有return語句時(shí),finally塊中的語句仍會(huì)執(zhí)行;
3.finally塊中的語句是在return語句執(zhí)行之后才執(zhí)行的,即函數(shù)返回值是在finally塊中語句執(zhí)行前確定的;
4.finally塊中不能包含return語句。
總結(jié):finally在return前執(zhí)行,在finally的操作,不會(huì)改變已經(jīng)確定的return的值,
finally不能加return語句。出現(xiàn)異常,先找是否有處理器可以處理這個(gè)異常.再finally。