您的位置:首页 > 职场人生

一道Java面试题,由于catch 捕获异常的原理

2017-05-22 22:43 459 查看
有如下代码:

class Annoyance extends Exception {}

class Sneeze extends Annoyance {}

 

class Human {

 

    public static void main(String[] args)

        throws Exception {

        try {

            try {

                throw new Sneeze();

            }

            catch ( Annoyance a ) {

                System.out.println("Caught Annoyance");

                throw a;

            }

        }

        catch ( Sneeze s ) {

            System.out.println("Caught Sneeze");

            return ;

        }

        finally {

            System.out.println("Hello World!");

        }

    }

}

经过测试输出如下结果:

Caught Annoyance

Caught Sneeze

Hello World!

按一般思路来说 throw a ,a 应该是Annoyance类型对象,不应该被第二个catch捕获了,但是实验结果证明被第二个catch捕获了。

会不会 catch 判断一个异常对象 是 通过 异常对象的运行时类型来判断的,a 的运行时类型是Sneeze ,如果是这样就能解释通了。

class Annoyance extends Exception {}

class Sneeze extends Annoyance {}

 

class Human {

 

    public static void main(String[] args)

        throws Exception {

        try {

            try {

                throw new Sneeze();

            }

            catch ( Annoyance a ) {

                System.out.println("Caught Annoyance");

                //加了红色部分的测试语句

                if(a instanceof Sneeze){

                    System.out.println("true");

                }else{

                    System.out.println("false");

                }

                throw a;

            }

        }

        catch ( Sneeze s ) {

            System.out.println("Caught Sneeze");

            return ;

        }

        finally {

            System.out.println("Hello World!");

        }

    }

}

测试结果:

Caught Annoyance

true

Caught Sneeze

Hello World!

实验结果验证了上面的猜想,但是本人没有去查看源代码,故这还是一种猜想~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java
相关文章推荐