当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How shold I handle a NullPointerException in PhoneDirectory program

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: