加载类时出现NullPointerException

时间:2016-01-19 06:01:39

标签: java nullpointerexception

以下代码给出了NullPointerException:

badOb = Class.forName("sample");
        try {
            Object obj = badOb .newInstance();
        } catch (ThreadDeath e) {
            throw e;
        } catch (Throwable e) {
            if (expectedException.isInstance(e)) {
                out.println("Expected runtime exception: " + e);
                return 0;
            } else {
                out.println("Unexpected runtime exception: " + e);
                return 1;
            }
        } 

但是当我添加一个如下的打印语句时:

 badOb = Class.forName("sample");
         out.println("hello");
        try {
            Object obj = badOb .newInstance();
        } catch (ThreadDeath e) {
            throw e;
        } catch (Throwable e) {
            if (expectedException.isInstance(e)) {
                out.println("Expected runtime exception: " + e);
                return 0;
            } else {
                out.println("Unexpected runtime exception: " + e);
                return 1;
            }
        } 

它运作正常并给出预期的异常。

我检查过,badob对象不是NULL。当我查看字节码时,添加print语句时,以下行是额外的:

aload_3        
ldc     #19; //String  hello           
invokevirtual   #1

有人可以帮助我理解它吗?

我的java环境是:

 java version "1.5.0"
 Java(TM) 2 Runtime Environment, Standard Edition

修改 如果我引入几秒钟的延迟而不是print语句,它也会按预期工作。

0 个答案:

没有答案