java的一些题目
阅读程序题, 写出结果并写出原因
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Test {
private static void fun1() throws MyException {
throw new MyException("An MyException object is thrown in fun1().");
}
private static void fun2() throws MyException {
try {
fun1();
}
catch(
NullPointerException ex) {
System.out.println("NullPointerException:"+ex.getMessage());
}
finally {
System.out.println("Go through finally code in fun2().");
}
}
public static void main (String[] args) {
try {
fun2();
}
catch(MyException ex) {
System.out.println("MyException:"+ex.getMessage());
}
catch(Exception ex) {
System.out.println("Exception:"+ex.getMessage());
}
}
}
------解决方案--------------------
调用fun2(),然后调用fun1(),在fun1()中会抛出一个异常
MyException,但是fun2()尤其定义可知,它并不会进行处理,
而是在其执行完之后将异常再抛出去(抛给调用者),所以
fun2()会执行到finally语句块,先输出"Go through finally ...",
然后再回到main方法中调用fun2()后捕获异常的catch(MyException),
所以也就会输出“MyException: An MyException ...”。
------解决方案--------------------
输出:
Go through finally code in fun2().
MyException:An MyException object is thrown in fun1().