• Post Reply Bookmark Topic Watch Topic
  • New Topic

how should null pointer exception be avoided in a program  RSS feed

 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How should null pointer exception be avoided in a program. Should each and every place of access of a variable be checked for null and if null is there own customized exception should be thrown. Is this approach correct for avoiding null pointer exception.

thanks
 
sai rama krishna
Ranch Hand
Posts: 536
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can check beforehand

Object Obj1 = getTheNullObject();
if (NullObj != null)
{// to avoid NullPointerException
NullObj.workwithit();
}

as given here
http://www.udemy.com/blog/java-null-pointer-exception/
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.
should I throw a customized own exception in the else part? Or in the else part nothing should happen?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How could the else part possibly execute?
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Monica. Shiralkar wrote:. . . Should each and every place of access of a variable be checked for null . . .
No. There are some places where nulls are unavoidable. Look at a binary tree for example. Elsewhere, stop nulls getting into your code in the first place.
Make sure every field is initialised to a “real” value.
No, you should not create your own exception for nulls; use NullPointerException. If any code tries to pass a null to a constructor or method, throw that exception. There are ready‑made methods for that.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should only use if (obj != null) … in situations where nulls are unavoidable.
 
Monica Shiralkar
Ranch Hand
Posts: 922
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all.

How could the else part possibly execute?


If ---when object is not null
Else---when object is null
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Monica. Shiralkar wrote:Thanks all.

How could the else part possibly execute?


If ---when object is not null
Else---when object is null
Not at all. You haven't read your own post which that was a reply to.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!