问题
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.
回答1:
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.
回答2:
A database lookup is a case where "no value found" is an expected occurrence. Exceptions are for handling exceptional circumstances that do not happen in normal use.
The cleanest way is to change your database API to return null on no value found. Then you do not have to worry about try/catch blocks at all and just propagate the null.
A nice side bonus is that using exceptions for flow control is relatively slow, so you will see nice performance improvements.
回答3:
It's 6 of 1 and 1/2 dozen of another. It really depends on what you want to do with the end result and if doSomething() is going to be used outside of this single use-case. The advantage of not throwing an exception is that you can return a known value when the exception occurs.
回答4:
Either approach is acceptable. The most important thing is that you document the behavior of your function.
If db.getValue()
cannot return null
, then the second option is probably easier. If it can, however, then you want a way to know whether the value is null
or there is none.
Some standard library classes do it both ways, implementing one function that throws an exception and another that returns null
.
回答5:
I am planning to do something like this (documented here):
public class NullUser extends User {
public static final NullUser INSTANCE = new NullUser();
public static NullUser getInstance() {
return INSTANCE;
}
@Override
public boolean isAuthenticated() {
return false;
}
private NullUser() {
}
}
public User getUser() {
if (/*some condition*/) {
return user;
} else {
return NullUser.getInstance();
}
}
if (obj.getUser().isAuthenticated() {
// allow
}
来源:https://stackoverflow.com/questions/9775471/get-around-javas-try-catch-and-keep-the-code-clean-without-returning-a-null