Hasan Abdullah Hasan Abdullah - 5 days ago 5
Java Question

For JSONArray parsing: TRY inside LOOP or LOOP inside TRY?

I've a JSONArray. I want to parse it into JSONObject. So Loop and try-catch are must.

Silly question is: Should I use FOR loop inside the TRY or reverse? Is it really matter or both are same?

Please tell me the best practice (if both are not same).

FOR loop inside the TRY:



try {
for(i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
//do something
}

} catch (JSONException e) {
e.printStackTrace();
}





TRY inside the Loop



for(i=0; i<jsonArray.length(); i++){

try {
jsonObject = jsonArray.getJSONObject(i);
//do something
} catch (JSONException e) {
e.printStackTrace();
}

}


Which one is preferable?

Answer

It depends on the scenario. If there are chances to get exception in any iteration of the loop, then I think try inside the loop is better. Because, after catching exception the loop will continue. But, It the try is out side of the loop, then the loop will break. I'll definitely go for try in the loop as it is more optimal.

Comments