Java(异常)

来源:互联网 发布:vb计算器代码 编辑:程序博客网 时间:2024/06/06 12:46
//下面程序是否能编译通过,如果可以,输出内容是什么public class Test {public static void main(String[] args) {Parent p = new Child();p.output();}}class Parent{public void output()throws NullPointerException{System.out.println("parent");}}class Child extends Parent{public void output() throws Exception {System.out.println("child");}}

答案:不能编译通过,子类中方法抛出的异常范围不能大于父类中方法抛出的异常范围。

/* * 下面程序输出什么 */public class Test2 {public static void main(String[] args) {try {String s = null;return;} catch (Exception e) {System.out.println("exception");}finally{System.out.println("finally");}}}
输出:finally。finally最终都会执行,在return返回之前会执行finally块

/* * 下面程序输出什么 */public class Test2 {public static void main(String[] args) {try {String s = null;System.exit(0);} catch (Exception e) {System.out.println("exception");}finally{System.out.println("finally");}}}
什么也不会输出,
System.exit(0);是立刻停止程序运行,finally块不会执行。
/* * 下面程序能否编译通过 */public class Test3 {public static void main(String[] args) {Test3 test3 = new Test3();test3.doSomething();}public void doSomething()throws ArithmeticException{System.out.println("do something");}}

答案:可以。

Java异常分为两大类:Checked Exception 和 RuntimeException,RuntimeException不需要在编译期进行处理,ArithmeticException属于RuntimeException


/* * 下面程序能否编译通过 */public class Test3 {public static void main(String[] args) {Test3 test3 = new Test3();try {test3.doSomething();} catch (Exception e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} }public void doSomething()throws IOException{System.out.println("do something");}}

答案:不能

程序会自上而下匹配每个carch块,当执行到第一个carch块时,因为Exception是IOException的父类,所以能匹配到。那下方的carch块永远不会被匹配到,编译错误。

在编写多个carch块时,要注意自上而下异常匹配的范围依次扩大。


0 0
原创粉丝点击