0

首先,这是我的代码:

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 级别引发异常?我希望这是个玩笑...

4

3 回答 3

4

IOEXception与 throwable 一起使用,您需要min API 9.. 检查

http://developer.android.com/reference/java/io/IOException.html#IOException(java.lang.Throwable )

于 2013-01-17T11:01:20.410 回答
2

您可以在 Eclipse 中更改 MIN api 级别

如果你进入你的清单文件并设置

    <uses-sdk android:minSdkVersion="8" /> <!--in your case -->

然后,您将整个项目从至少运行 2.2.X 更改为 2.3.X

在您仍在构建应用程序时,您可以随时更改最低 API 级别。

于 2013-01-17T10:59:00.713 回答
2

finally 块中的代码将始终被调用,即使 try 块中的代码抛出异常也是如此。至于 API 级别限制 - 这IOException(Throwable)是 API 级别 9 中添加的特定构造函数。

于 2013-01-17T11:00:24.577 回答