Friday, 9 August 2013

solution to Check for NullPointerException or ArrayOutOfBound Exception Java

solution to Check for NullPointerException or ArrayOutOfBound Exception Java

In the following code, How do i guard against
ArrayIndexOutOfBoundsException or NullPointerException because at some
point, comment line 2 is going to give me a null value for the last entry
in mydates[] or dates[mod] is going to throw an ArrayOutOfBoundException
if i do mod > dates.lenght in comment 2
if(dates.length >= 10){
mydates = new String[11];
int last = dates.length;
int mod = 0;
int add_mod = (int)Math.round((double)Math.round(last) /10);
for(int i =0; i < dates.length; i++){
if(mod >= dates.length){
break;
}
mydates[i] =
DateFormatter.GraphDateToString(DateFormatter.convertToDate(Long.parseLong(dates[mod])));
//line2
mod += add_mod;
}
}else {
mydates = new String[dates.length];
for(int i =0; i < dates.length; i++){
mydates[i] =
DateFormatter.GraphDateToString(DateFormatter.convertToDate(Long.parseLong(dates[i])));
}
}
the way i solved it was to iterate over the array again and check for null
values while populating a new array from there. But i want to find if
there is a better solution out there.

No comments:

Post a Comment