Other than catching the error, if you are going to work with something which might be null, you might want to throw in null checks.
What you could do to reduce the chances of having to make null checks, would be to never return null
from your methods, unless it is really necessary, for instance:
public IList<String> getUserNames()
{
//No usernames found...
return new ArrayList<String>();
//As opposed to returning null
return null;
}
By returning the empty list, a call to the above code would result into something like so: for(String name : this.getUserNames()) {...}
. If no user names where found, the loop will not execute.
If on the other hand, you return null, you would need to do something like so:
List<String> userNames = this.getUsernames();
if(userNames != null)
for(String userName : userNames) {....}