关于Java异常处理的一个有趣的代码的分析

看了这个博客http://blog.csdn.net/hguisu/article/details/6155636一开始并没有理解博主的代码的意思

代码如下:

package Test;  
  
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();  
        }  
    }  
}  

  查了好多资料都没有查出结果,困扰了我两天后,我突然意识到一个问题。

 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;  
        }  
    }  

 

这个方法执行中一定会抛出异常的,这是没毛病的,但是为什么调用他的调用者会接收不到这个异常呢?

我的猜想如下:

  问题就在于finally里面的一个return ret; 这样写代码的方式肯定是有问题的。finally中的代码是无论如何都要执行的。

所以,上面的那个方法是无论如何都有返回值的,这时候他的调用者接收到了他想要的返回值,就会误认为这个方法正确执行了,也就不会catch任何异常了。

 

不知道有没有人有更高明的理解,希望大佬们教教我,带我飞。

posted @ 2017-05-19 12:05  御坂美琴2604  阅读(188)  评论(0编辑  收藏  举报