THINKING IN JAVA 上的一道关于异常处理的题目

aizhongwang83 2008-04-24 04:32:39
class AbortedConstruction extends Exception {
public AbortedConstruction() {
super("Construction aborted");
}
}

class WithCleanup {
private boolean constructed = false;
public WithCleanup(boolean abort)
throws AbortedConstruction {
// Perform construction that might be
// unsucessful (and throw an exception) here.
if(abort) throw new AbortedConstruction();
System.out.println("After exception");
constructed = true;
}
public void cleanup() {
System.out.println(
"constructed = " + constructed);
if(constructed == true)
System.out.println("Cleaning up");
else
System.out.println(
"Constructor didn't finish,"+
"not cleaning up");
}
}
public class E14_CleanupFlag {
public static void main(String args[]) {
WithCleanup wc = null;
try {
wc = new WithCleanup(false);
} catch(AbortedConstruction e) {
System.out.println("Caught " + e);
} finally {
System.out.println(
"In finally 1, preparing to clean up");
wc.cleanup();
}
wc = null; // Very important!
try {
try {
wc = new WithCleanup(true);
} catch(AbortedConstruction e) {
System.out.println("Caught " + e);
} finally {
System.out.println(
"In finally 2, preparing to clean up");
wc.cleanup();
}
} catch(Exception e) {
System.out.println("Caught exception "+ e);
}
}
} ///:~
结果:
After exception
In finally 1, preparing to clean up
constructed = true
Cleaning up
Caught AbortedConstruction: Construction aborted
In finally 2, preparing to clean up
Caught exception java.lang.NullPointerException

我想知道Caught exception java.lang.NullPointerException怎么产生的,大家帮帮忙
...全文
78 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
胡矣 2008-04-24
  • 打赏
  • 举报
回复
wc = new WithCleanup(false);
这局的时候出现AbortedConstruction 异常.
所以没有生成新对象.wc为null.
运行到下面wc.cleanup(); 的时候出现java.lang.NullPointerException
ty8888 2008-04-24
  • 打赏
  • 举报
回复
帮上面的楼主顶上去~~~~~~~~!
zbo 2008-04-24
  • 打赏
  • 举报
回复
wc=null,
在wc=new WithCleanup(true)中,首先计算等式右边的值,再赋给wc,
在计算值的过程中抛出异常,程序跳转到finally段。
执行wc.cleanup(),因为wc是null,所以抛出空指针异常啊。
anqini 2008-04-24
  • 打赏
  • 举报
回复
wc.cleanup();最后一个这里出这个异常,因为wc = new WithCleanup(true);之后,构造方法里面出异常了,所以没有实例化其类,所以wc是个null,当你调用null.cleanup();方法的时候出这个异常
li_d_s 2008-04-24
  • 打赏
  • 举报
回复
wc = new WithCleanup(true);
这里,在执行new WithCleanup的时候出现异常就跑到catch里面去了wc根本没有被初始化,还是null,然后到了finally,wc.cleanup()当然就抛出空指针异常。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧