这是代码:

    Pair<Boolean, String> updateServer() {
        final String LOG_TAG = "WS.UST.updateServer";

        Pair<Boolean, String> retVal = null;

        URL url;
        String sRawResponse = null;
        JSONObject joResponse = null;
        HttpURLConnection connection = null;
        try {
            url = new URL("http://www.abc.in/v3.php");
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            connection.setDoInput(true);

            final int response = connection.getResponseCode();
            if (response != HttpURLConnection.HTTP_OK)
                throw new IOException("Server response code (" + String.valueOf(response) + ") is not OK.");

            InputStreamReader isReader = new InputStreamReader(connection.getInputStream());
            StringBuilder s = new StringBuilder();
            char[] cBuf = new char[1024];
            for (int cRead = isReader.read(cBuf, 0, 1024); cRead != -1; cRead = isReader.read(cBuf, 0, 1024))
                s.append(cBuf, 0, cRead);
            isReader.close();

            sRawResponse = s.toString();
            joResponse = new JSONObject(s.toString());

            retVal = new Pair<>(joResponse.optBoolean("success"), joResponse.optString("message"));
        } catch (IOException | JSONException e) {
            Log.d(LOG_TAG, sRawResponse == null ? "null" : sRawResponse);
            Log.d(LOG_TAG, joResponse == null ? "null" : joResponse.toString());
            e.printStackTrace();
            retVal = new Pair<>(false, e.getMessage());
        } catch (Exception e) {
            retVal = new Pair<>(false, e.getMessage());
        } finally {
            if (connection != null)
                connection.disconnect();
        }
        return retVal;
    }


Android Studio在第一个catch块的第二行中显示警告Value 'joResponse' is always 'null' more... (Ctrl+F1),我不明白为什么。谁能帮助我了解警告的原因?

最佳答案

这有点简单,但是需要您注意可能发生异常的流程。让我们讨论代码中引发异常的流程。

您在第一个catchIOException & JSONException中添加了两个例外。最初您有joResponse = null,现在在代码中向下移动。 IOException可以由InputStreamReader生成,到目前为止,您尚未为joResponse分配任何值。当您尝试从JSONException制作JSONObject时,还会引发String,因为此行会引发异常,因此在这里也不会再次为joResponse分配任何值。

因此,如果您的程序曾经到达第一个catch块,则可以确保joResponsenull。因此,Android Studio发出了警告。

10-08 17:32