问题描述
java version "1.7.0_75"
你好,
只是想知道比较下面两个函数的首选最佳做法是什么。
Just wondering what is the prefered best practice comparing the 2 functions below.
第一个抛出NullPointerException应该在调用函数中捕获。
如果存在空指针异常,则第二个返回false。
The first one throws a NullPointerException that should be captured in the calling function.The second one just returns false if there has been a null pointer exception.
抛出异常:
public void disconnect() throws NullPointerException {
if(mClientConnection == null) {
throw new NullPointerException("mClientConnection has an invalid reference");
}
if(mClientConnection.isConnected()) {
mClientConnection.disconnect();
}
mClientConnection = null;
}
只返回true或false:
Just return true or false:
public boolean disconnect() {
if(mClientConnection == null) {
log.log(Level.SEVERE, "Cannot disconnect as mClientConnection is null");
return false;
}
if(mClientConnection.isConnected()) {
mClientConnection.disconnect();
}
mClientConnection = null;
return true;
}
通常在过去我总是选择第二个返回true或者是假的。但现在我只是在寻找替代解决方案。
Normally in the past I have always gone with the second one by just return true or false. But so now I am just looking for alternative solutions.
非常感谢任何建议,
推荐答案
如果您编写其他开发人员将使用的API - 最好采用第二种方法,从客户方面处理起来更容易(也更清晰):
If you write an API that other developers will use - better take the second approach, it's easier (and cleaner) to handle from the "customer" side:
while (!disconnected()) {
// do something else
// sleep and try again
// etc
}
一般情况下 - 不要抛出你知道如何正常处理的异常!
In general - don't throw exceptions that you know how to handle gracefully!
这篇关于返回true或false或抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!