【问题标题】:catch Exception with add [duplicate]使用添加捕获异常 [重复]
【发布时间】:2014-04-15 19:19:39
【问题描述】:

我在main方法中写了这个语句 异常将在 (GuaranteeYears) 中,所以我将它放在 try 块中。

首先在main 中创建一个Store 对象并在参数中传递数字4,在Store 类中我将有一个名为arrProduct 的数组,其长度为4:

boolean flag1 = true;
while (flag1) {
    try {
        System.out.println("Ente GuaranteeYears");
        int GuaranteeYears=read.nextInt();

        StrongDevice s = new StrongDevice(code,type,price,Model,Capacity,GuaranteeYears); //the object

        flag1 = false;
        x.addProduct(s);
     }

这是我的添加方法

public boolean addProduct(Product p) {
    if(arrProduct.length==NumOfProduct)
        return false;

    arrProduct[NumOfProduct]=p;
    NumOfProduct++;
    return true;
}

我的问题是:当我创建对象并将其添加到数组时,它给了我NullPointerException - 为什么会这样?

【问题讨论】:

  • @SotiriosDelimanolis 我真的知道什么是空指针异常,但我不知道为什么会在这里发生?
  • NPE 发生的原因没有一百万个。阅读答案。您会发现它发生的原因,并将其应用到您的场景中。

标签: java exception try-catch


【解决方案1】:

据我了解,导致NPE 的行是

x.addProduct(s);

这很可能是由于数组arrProduct 未初始化而导致NPE 在被访问时引起的。

要解决此问题,请验证 arrProduct 在创建 Store 对象时始终正确初始化。

【讨论】:

  • @BSMN 能否请您发布整个Store 课程?
  • 是的,谢谢,我将数组初始化为public,然后在构造函数中再次初始化! ,它的工作现在,谢谢你的帮助
  • @BSMN 不客气,我很乐意提供帮助。不要忘记为正确的答案投票并选择一个正确的答案。
猜你喜欢
  • 2012-07-13
  • 2011-12-07
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
相关资源
最近更新 更多