我正在努力清理我的一些代码,然后我发现我不确定哪条路线会更好.
目前我在我的大多数方法上都有一个try catch块,它最后处理了一些单独的异常,但我认为有更多尝试catch块会更好的维护.但是,在分解代码的过程中,我遇到了为同一类型的异常编写多个块的问题.我可以看到为每个部分编写一个块的好处,因为我可以更详细地说明它失败的原因.
我的问题是......这样做有不利之处吗?我有没有看到性能问题或其他隐藏的怪物?
此外,在方法中处理多个异常的首选方法是什么?是否有行业标准?
为了更好地说明我的观点,这里有一些伪代码
//multiple try catch for same exception
try {
//some code here
} catch (MyException e) {
//specific error message here
}
try {
//some different code here
} catch (MyException e) {
//more specific error message indicating a different issue
}
Run Code Online (Sandbox Code Playgroud) java version "1.7.0_75"
Run Code Online (Sandbox Code Playgroud)
你好,
只是想知道比较以下 2 个函数的首选最佳实践是什么。
第一个抛出应该在调用函数中捕获的 NullPointerException。如果存在空指针异常,则第二个只会返回 false。
抛出异常:
public void disconnect() throws NullPointerException {
if(mClientConnection == null) {
throw new NullPointerException("mClientConnection has an invalid reference");
}
if(mClientConnection.isConnected()) {
mClientConnection.disconnect();
}
mClientConnection = null;
}
Run Code Online (Sandbox Code Playgroud)
只需返回真或假:
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;
}
Run Code Online (Sandbox Code Playgroud)
通常在过去,我总是通过返回 true 或 false 来选择第二个。但现在我只是在寻找替代解决方案。
非常感谢您的任何建议,