How to avoid null pointer exception in java -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
i curious know proper way avoid nullpointerexception
s.
try { string name = null; system.out.println("name=" + name.tostring()); } catch(exception e) { system.out.println("exception occured" + e.getmessage()); }
here catching , showing exception message. want know proper way handle or avoiding such situations.
other catching error, if going work might null, might want throw in null checks.
what reduce chances of having make null checks, never return null
methods, unless necessary, instance:
public ilist<string> getusernames() { //no usernames found... return new arraylist<string>(); //as opposed returning null return null; }
by returning empty list, call above code result so: for(string name : this.getusernames()) {...}
. if no user names found, loop not execute.
if on other hand, return null, need so:
list<string> usernames = this.getusernames(); if(usernames != null) for(string username : usernames) {....}
Comments
Post a Comment