我知道,對於你們許多人來說,這可能是一個愚蠢的問題,但我正在學習android/java,我仍然有一些概念不清楚。返回聲明與try/catch
在這種情況下,我不確定在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'被返回,它不是null。 – Petter
'返回null;'是無法訪問的代碼。 – Maroun
@Petter所以,如你所說,如果沒有發生異常並且它通過try塊,它將返回try塊中的內容並跳過返回null值 – masmic