`
cage918
  • 浏览: 19243 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

有关java的异常处理

    博客分类:
  • java
阅读更多
看下下面这段代码:
public class TestException {

    public TestException() {

    }

    boolean testEx() throws Exception{
       boolean ret = true;

        try{

            ret = testEx1();

        }catch (Exception e){

            System.out.println("testEx, catch exception");

            ret = false;

            throw e;

        }finally{

            System.out.println("testEx, finally; return value="+ret);

            return ret;

        }

    }
    boolean testEx1() throws Exception{

        boolean ret = true;

        try{

            ret = testEx2();

            if (!ret){

                return false;

            }            

System.out.println("testEx1, at the end of try");

            return ret;

        }catch (Exception e){

            System.out.println("testEx1, catch exception");

            ret = false;

            throw e;

        }

        finally{

            System.out.println("testEx1, finally; return value="+ret);

            return ret;

        }

    }
    boolean testEx2() throws Exception{

        boolean ret = true;

        try{

            int b=12;

            int c;

            for (int i=2;i>=-2;i--){

                c=b/i;

                System.out.println("i="+i);

            }

            return true;

        }catch (Exception e){

            System.out.println("testEx2, catch exception");

            ret = false;

            throw e;

        }

        finally{

            System.out.println("testEx2, finally; return value="+ret);

            return ret;

        }

    }

    public static void main(String[] args) {

        TestException testException1 = new TestException();

        try{

            testException1.testEx();

        }catch(Exception e){
            e.printStackTrace();

        }

    }

}

结果是什么?

注意java中能改变控制权的语句,比如return,break,continue,throw等。写代码的时候一定要注意finally里面的return语句,否则可能导致上层程序无法捕获内部方法抛出的异常。
分享到:
评论
3 楼 ljm3256748 2008-06-12  
哈哈,根本就没看
2 楼 ftj20003 2008-06-12  
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
这是打印的结果,之所以这样是在testEx2的finally语句包含return,所以在catch块里面的新异常根本就没来及的抛出就跳出了。导致上层没有捕获到相应的异常仅执行finally里面的语句。
1 楼 yiding_he 2008-06-12  
好难看,博主要排一下版才行。

相关推荐

Global site tag (gtag.js) - Google Analytics