• Post Reply Bookmark Topic Watch Topic
  • New Topic

Parameter validation - checked or unchecked exception or...  RSS feed

 
Dan Pollitt
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a method:

public Object doWork(Object obj)
{
...
}

if obj is null and I do no checking a NullPointerException will be raised.

My question is what is the best approach to take in parameter validation from a design point of view. Let's say that in this case null is not a valid parameter. I'd like to get input on whether I should:

a) Leave the NPE to be thrown - it's the callers fault
b) Check for null - if null throw an IllegalArgumentException (runtime exception)
c) Check for null - throw a declared/checked exception (caller must handle YouPassedAnIllegalParamException)
d) return from the method with something
e) something else...

In this case I don't believe that the caller would be able to correct what had happened (they had used an uninitialised reference) so can't see the advantage of having a checked exception...

What do you guys think?
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Dan,

The answer of your question is very simple.
See, null is expected from the parameter and is part of ur logic and you want to handle it, then handle it and do what ever u want to do e.g. throw null pointer exception/ur own exception/ write some code to handle it.

But if u dont expect anyhting like null, then dont do any null ponter cheking. Null pointer will come iff there is some problem in network/database/etcetc, then dont do anything cause u cant handle it.

Hope this clears.

Sandeep Jindal
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!