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

I have a JSONArray. I want to parse it in a JSONObject. So Loop and try-catch should. Stupid question: should I use a FOR loop inside TRY or vice versa? Does it really matter or are both the same?
Please tell me about the best practice (if both of them do not match).

FOR loop inside 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?

+4
source share
7 answers

It depends on how serious you are about data integrity.

  • , , , catch .

  • try , , catch . , .

. , , = 4

try {
    for(i=0; i<10; i++){
        System.out.println("" + i);
    }

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

-

0
1
2
3
Exception

for(i=0; i<10; i++){

    try {
        System.out.println("" + i);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

0
1
2
3
Exception
5
6
7
8
9
+5

TL, DR: , .


, /, ,

[{"name":"Apple"},{"name":"Banana"},{"name":"Mango"}]

, , , TRY Loop.

, , FOR TRY.

, , :

[{"name":"Apple"},{"name":"Banana},{"name":"Mango"}] // notice the missing " after Banana

TRY

[{"name":"Apple"},{"name":"Mango"}]

FOR TRY .

+2

. , , . , , . , , . ​​, .

+1

( ). try , . try, catch.

continue break ? , ? . , .

+1

, for, - 3- , .

, try catch , .

0

try catch , . , , for. , "TRY " .

0

, . , , :

    try {
        JSONArray jsonArray = new JSONArray(jsonString);

        int count = jsonArray.length(); 
        for(int i=0 ; i< count; i++){   
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println("jsonObject " + i + ": " + jsonObject);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

, do-catch

0

Source: https://habr.com/ru/post/1662365/


All Articles