这是代码:
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在第一个捕获块的第二行中显示了警告Value 'joResponse' is always 'null' more... (Ctrl+F1)
,我无法理解原因。谁能帮助我了解警告的原因?
这很简单,但是需要您注意可能出现例外的流程。让我们讨论您的代码中提出的异常的流程。
您在第一个catch
块IOException & JSONException
中添加了两个例外。最初,您有joResponse = null
,现在在代码中向下移动。IOException
可以由InputStreamReader
生成,到目前为止,您还没有为joResponse
分配任何值。当您尝试从String
制作JSONObject
时,进一步提高了JSONException
,因为此行将提高异常,因此joResponse
也不会在此处再次分配任何值。
因此,如果您的程序曾经达到第一个catch
块,则确保joResponse
为null
。因此,Android Studio的警告。
这是因为,如果发生IOException,则代码停止在" new URL(..(;"处执行。或Connect.getResponsecode((等。在分配Joresponse之前,将发生任何IOException。因此,在IOException Catch Block中,Joresponse始终是无效的。如果发生了jsonexception,则在分配时发生了一些事情,因此Joresponse是无效的。
IOException | JSONException
(如果发生(将始终发生在joResponse
在您的代码中初始化。因此警告。