日期:2014-05-20  浏览次数:20959 次

第一次 发问 请教一个小问题 finally 和 return

public   class   TestTryCatch   {
private   boolean   method1()   throws   Exception{
boolean   have   =   false;
try{
String[]   str1   =   { "123 ", "456 "};
System.out.println( " "   +str1[3]);
have   =   true;
}catch(Exception   e){
System.out.println( "In   method1     This   is   exception=   "+e);
throw   e;
}finally{
have   =   true;
return   have;
}
}

private   void   method2(){
try   {
if(method1()){
System.out.println( "IN   method2   run   ");
}
}   catch   (Exception   e)   {
System.out.println( "In   method2   exception= "+e);
e.printStackTrace();
}
}

public   static   void   main(String[]   args)   {
TestTryCatch   tt   =   new   TestTryCatch();
try   {
tt.method2();
}   catch   (Exception   e)   {
e.printStackTrace();
}
}

}

输出:
In   method1     This   is   exception=   java.lang.ArrayIndexOutOfBoundsException:   3
IN   method2   run  

问一下?
为什么   In   method2   exception   没有输出来呢?


------解决方案--------------------
因为method1()永远返回的是true 也就是说method2不会发生异常
------解决方案--------------------
因为你使用了finally{},所以method1()中的异常e永远也不会掷出,method2()也就不会捕捉到这个异常

------解决方案--------------------
method1()必须要有try{}catch(Exception e){}
--------------
否则报错
------解决方案--------------------
分析一下,执行过程就清楚了!
首先建立TestTryCatch的对象tt,然后调用method2()方法.下面是执行method2().
一句一句来,先try{}catch语句,在它之中是if语句,if语句调用method1()方法.
接下来去执行method1()函数,在你的menthod1()中,主体是try{}catch{}finally
语句,相信你一定知道,finally特性,所以最终method1返回的是true.这也就决定
在method2()的try不会抛出异常而输出 IN method2 run