• Post Reply Bookmark Topic Watch Topic
  • New Topic

try catch or if else ?  RSS feed

 
nimo frey
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:


 
Paul Sturrock
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".
 
Stephan van Hulst
Saloon Keeper
Posts: 7964
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exactly. Just use if statements.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!