First, here is my code :
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;
}
My problem is that I was first only declaring my method throwing an IOException. But if it happens, I suppose the HttpsUrlConnection would not be disconnected.
So I thought catching the Exception, rethrowing it so when my method is called by another class I can handle a network/connection error and tell the user about it, and so the code will still run the finally block to close the connection.
First, am I right? Or is there another way to do this?
I don’t care about the try{} catch{} inside the method, I just want to be sure that the connection and streams will always be closed, whether an exception is thrown or not.
The other problem is the catch{} block where I throw the exception. Eclipse tells me:
Call requires API level 9 (current min is 8): new java.io.IOException
Seriously, I can’t throw an exception using an API level below 9? I hope it’s a joke…
Code in a finally block will always be called, even if the code in the try-block throws an exception. As for the API level restriction – it’s the specific
IOException(Throwable)constructor that was added in API level 9.