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).
try {
for(i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
//do something
}
} catch (JSONException e) {
e.printStackTrace();
}
for(i=0; i<jsonArray.length(); i++){
try {
jsonObject = jsonArray.getJSONObject(i);
//do something
} catch (JSONException e) {
e.printStackTrace();
}
}
Which one is preferable?
It depends on how you serious you are about the integrity of the data.
The first example, will run the loop until an exception occurs, and once it does, the catch block is invoked and the loop will no longer run.
However the second example will enter the try block and try executing the code and if there is an exception, the catch block is invoked and the exception is sorted out. However the loop doesn't end, the next iteration will run right after.
Here is an example. We will consider there is some exception occurring when i = 4
try {
for(i=0; i<10; i++){
System.out.println("" + i);
}
} catch (Exception e) {
e.printStackTrace();
}
Output -
0
1
2
3
Exception
And
for(i=0; i<10; i++){
try {
System.out.println("" + i);
} catch (Exception e) {
e.printStackTrace();
}
}
Output
0
1
2
3
Exception
5
6
7
8
9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With