帮忙看下这段代码,为啥那个afafafa没有打印出来?
public class Demoe {
  public  void f()  {
    System.out.println("Throwing MyException from f()");

   }
  public static void main(String[] args) {
   Demoe aa = null;



    try {
        aa.f();  throw new NullPointerException("afafafa");
    } catch(NullPointerException e) {
        System.out.println("Caught Exception1"+e.getMessage());
        e.printStackTrace();
    } finally {
        System.out.println("Made it to finally");
    }

}   

}

Caught Exception1null   为啥那个afafafa没有打印出来,getMessage()不是打印的异常的详细消息字符串吗?
 java.lang.NullPointerException
    at Demoe.main(Demoe.java:14)
Made it to finally

5个回答

 try {
        aa.f();  //执行到这一句就报空指针了,aa=null
                throw new NullPointerException("afafafa");//这句还没执行到
    } catch(NullPointerException e) {
        System.out.println("Caught Exception1"+e.getMessage());
        e.printStackTrace();
    }

把throw 异常的逻辑放在方法f()中,然后在再main中捕获异常

u014307911
antfor 回复lbcab: public void f()throw ex......
4 年多之前 回复

nullpointerexception

java.lang.NullPointerException

                空指针
                                    指代错误或者是位置放错

要先 Demo aa = new Demo();

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问