I have this piece of code:
private void myFunc(){
obj = doSomething();
//If value is found, doX()
//If value is not found, doY()
}
private obj doSomething(){
//Do some stuff
//Hit database to get some value
obj = db.getValue(); //This func throws an exception if no value is found
}
Now, my question is:
1. Should I do: doSomething() throws ValueNotFoundException and catch it in myFunc()
2. Or catch it in doSomething() and return null? (a very bad approach though). And then check for null in myFunc()
Update:
1. Value not found is something which is probable and not an error.
解决方案
Well, is value not found something exceptional (indicating an error) or probable? If it is absolutely not possible that doSomething() can't find what it needs, this is an error. I guess myFunc() is not the right place to handle such error.
If doSomething() sometimes can't find this or that (because the input is incorrect, misconfiguration, etc.) then it should not throw an exception and let the client handle this expected situation. However null is not the best return value. Instead consider null-object design pattern or some wrapper like Option[T] in Scala.
This is one of the reasons why InputStream is not simply throwing EOFException when it reaches end of file. This is not an unexpected situation.
In Java I try to follow some techniques/naming conventions to make null more obvious:
private Obj tryReturningSomething()
private Obj returnSomethingOrNull()
Also you can always use JavaDoc to document possible return value. I agree returning null is not the best approach (e.g. when method returns a collection, I always return an empty one instead of null) but in your case it is still better than throwing an exception to be caught one stack frame above. This is wasteful, harder to maintain and read. Consider having two version - one returning null and one throwing an exception, wrapping the first one.
Exception handling was invented to handle errors, not to control the program flow.