【发布时间】:2014-03-10 23:10:13
【问题描述】:
我知道对你们中的许多人来说这可能是一个愚蠢的问题,但我正在学习 android/java,但我仍然有一些不清楚的概念。
在这种情况下,我不确定在 try/catch 块中使用 return 语句的最佳方式是什么。
这就是我在需要使用它的地方声明我的方法的方式:
public JSONArray parseXmlResponse(String response) {
JSONArray addressComp = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(response);
addressComp = jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
}catch (JSONException e) {
e.printStackTrace();
}
return addressComp;
}
据我所知,这里的方法总是返回“addressComp”,即使它为空。
但我看到其他人会以其他方式这样做:
public JSONArray parseXmlResponse(String response) {
JSONArray addressComp = null;
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(response);
addressComp = jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
return addressComp;
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
但这让我有点困惑。
通过在此处设置return null 不会将值设置为始终返回为null,即使addressComp 具有实际值?
【问题讨论】:
-
如果没有发生异常,则返回发生在
try块的末尾。此时返回addressComp,它不为空。 -
return null;是无法访问的代码。 -
@Petter 所以,正如你所说,如果没有发生异常并且它通过 try 块,它会返回 try 块中的内容并跳过返回的 null 值
-
@ᴍarounᴍaroun 不,不是。如果 try 块中的语句之一抛出 JSONException,它将不会到达
return addressComp;,因此会在打印堆栈跟踪后到达return null;。 -
@blalasaadri 你是对的。
标签: java android return try-catch