Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Ranch Hand
Posts: 952
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
 
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: 952
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?
 
Author and ninkuma
Marshal
Posts: 66535
160
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?
 
Marshal
Posts: 58345
178
  • 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: 58345
178
  • 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: 952
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: 58345
178
  • 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!