首先,这是我的代码:
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{}
我抛出异常的块。日食告诉我:
Call requires API level 9 (current min is 8): new java.io.IOException
说真的,我不能使用低于 9 的 API 级别引发异常?我希望这是个玩笑...