Revathi
Revathi

Reputation: 1203

How to handle NullpointerException in this case

This is my for loop function inside the servlet

Here i have a question . The Data will be passed from the USER Interface to this .

In some conditions , some information (For example symbol or side ) may not be passed , then in those conditions , i am getting NullPointreException as null would be supplied to it .

List<Bag> bags = new ArrayList<Bag>(bagdata.length);

for (FormBeanData ld : data) {
    Bag bag = new Bag();
    bag.symbol = ld.getSymbol();
    bag.side = ld.getSide();
    bags.add(bag );
}

Is there anyway we can handle such situations ??

Thank you .

Upvotes: 0

Views: 127

Answers (2)

Matteo
Matteo

Reputation: 14930

The code you submitted most likely does not even compile: bags.add(Bag) does not make sense. You need to add the bag object (the instance), not Bag (the class).

In any case if you want to check if a reference is null just check it:

if (myobject != null) {
    myobject.myfield = ... // myobject is not null
} else {
    // ignore, print an error, do what is required to do
}

You also have to check before iterating

if (collection != null) {
  for (Object o : collection) {
  }
}

Upvotes: 2

NCode
NCode

Reputation: 2808

Just check if any of the values is equal to null

List bags = new ArrayList(bagdata.length);
for (FormBeanData ld : data) {
    if(ld!=null && ld.getSymbol()!=null && ld.getSide()!=null) {
        Bag bag = new Bag();
        bag.symbol = ld.getSymbol();
        bag.side = ld.getSide();
        bags.add(Bag);
    }
}

Upvotes: -1

Related Questions