This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
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

try catch or if else ?  RSS feed

 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is better code:

this:



or that:



Where lies the difference?

When using something like this from Google guave, I cannot see the benefit to use checkNotNull against the methods described above. Moreover, I cannot use checkNotNull in if-else as it returns npe if id is null.

Preconditions.checkNotNull(id);
it throws NPE, if id is null. When using this in code:


 
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Preconditions.checkNotNull(id);
it throws NPE, if id is null.


That sounds like poor coding. The method is ultimately pointless if what you say is true.

Exceptions as conditions is usually considered an anti-pattern (except where the exception shows truly exceptional behaviour, if you follow). Throwing a NullPointerException if you cannot find a user is confusing. Think in terms of supporting this software without being able to see the code; what does the NPE mean? Also remember that throwing exceptions is more expensive. When an exception is thrown a stack trace is produced.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you.

I use "if else" instead of "try catch" or the nonsense methods of Google Guave "Preconditions.checkNull(object)" or Apaches "Validate.notNull(object)". I dont see any advantageous of using this guave or apaches method instead of "if else".
 
Saloon Keeper
Posts: 8617
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly. Just use if statements.
 
Marshal
Posts: 58414
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really don't want null values getting into your method, or null values returned from it, you should simply throw the NPE out of your method. Like what it says in the old-fashioned Hashtable#put() method. It is probably a bad idea to let nulls into your programming, but catching an NPE and returning null doesn't help.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!