Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

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?

like image 377
Hasan Abdullah Avatar asked Jan 05 '23 00:01

Hasan Abdullah


1 Answers

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
like image 55
SanVed Avatar answered Jan 13 '23 13:01

SanVed