【发布时间】:2013-01-17 10:55:32
【问题描述】:
首先,这是我的代码:
public static boolean loginValide(final String username, final String password) throws IOException {
final boolean valide = false;
final String postData = "somePostParameters";
URL url;
HttpsURLConnection connexion;
url = new URL("someUrl");
connexion = (HttpsURLConnection) url.openConnection();
try {
connexion.setDoOutput(true);
final DataOutputStream dos = new DataOutputStream(connexion.getOutputStream());
dos.writeBytes(postData);
dos.flush();
dos.close();
final int responseCode = connexion.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_ACCEPTED) {
// ...
}
else {
// ...
}
} catch (final IOException e) {
throw new IOException(e); /* I am retrowing an exception so the
finally block is still called */
}
finally {
connexion.disconnect(); // Close the connection
}
return valide;
}
我的问题是我首先只是声明我的方法抛出了一个 IOException。但如果发生这种情况,我想 HttpsUrlConnection 不会断开连接。 所以我想捕获 Exception,重新抛出它,这样当我的方法被另一个类调用时,我可以处理网络/连接错误并告诉用户它,所以代码仍然会运行 finally 块关闭连接。
首先,我说的对吗?还是有其他方法可以做到这一点?
我不关心方法内部的try{} catch{},我只想确保连接和流将始终关闭,无论是否抛出异常。
另一个问题是我抛出异常的catch{} 块。 Eclipse 告诉我:
Call requires API level 9 (current min is 8): new java.io.IOException
说真的,我不能使用低于 9 的 API 级别引发异常?我希望这是个玩笑...
【问题讨论】:
-
finally 块中的代码将始终被调用,即使 try 块中的代码抛出异常。
-
@archer 反引号用于内联代码,而不是每个保留字。停止使用它们太多。如果有代码块,把它们作为一个代码块。
-
你为什么不
throw e? -
另外,finally 块总是被调用
-
@njzk2 完美,我不知道我能做到这一点。谢谢!
标签: java android api exception android-2.2-froyo