-1

I am trying to create an addChangeEntry method for my PhoneDirectory program, its function is to search and either add a new entry to the Directory if the name passed does not exist, or if the contact already exists, updates their number.

I keep getting NullPointerExceptions, as I believe that my value of x equals null. After learning this I tried to catch and handle the Exception, but I am still receiving NullPointerExceptions.

addChangeEntry code:

public String addChangeEntry(String name, String telno) {
    for (DirectoryEntry x : theDirectory) {
        try {
            if (x == null) {
                Logger logger = Logger.getLogger(ArrayPhoneDirectory.class.getName());
                logger.log(Level.WARNING, "User with no name found");
                continue;
            }

            else if (x.getName().equals(name)) {
            x.setNumber(telno);
            return x.getNumber();
            }

            add(name, telno);
        }
            catch (Exception ex) {
        System.out.println("Exception found");
        throw ex;
            }
        }
    return null;
}

Any help on how to handle this exception would be much appreciated, as it is currently halting my testing of the program.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joe Perkins
  • 261
  • 3
  • 9
  • 17

1 Answers1

0

if your assumption is true and it's about x being null.Then this may be your problem,after catching the exception, you throw it by throw ex; that's why you get still it. If you don't want the program to stop, just remove it from your code.

richard
  • 742
  • 2
  • 9
  • 21
  • I now have a feeling it may be that theDirectory is null, as all thats happening in my for-loop then is that its searching theDirectory array for users, when there are none, causing the exceptions. Does this sound possible? – Joe Perkins Apr 23 '14 at 15:43
  • then you should examine `theDirectory` at very first or move `try` to before `for` – richard Apr 23 '14 at 15:45