Home > other >  Try Catch in Java | Json still crashes
Try Catch in Java | Json still crashes

Time:03-09

                 try {
                          Log.e("getTrackerSettings | ", json);
                          trackerSettings = new Gson().fromJson(json, typeToken);
                      } catch ( IllegalStateException e) {
                          Log.e("getTrackerSettings inside catch | ", "");
                          e.printStackTrace();
                          trackerSettings = new TrackerSettings(1, "Hello", "73");
                      }

This code snippet will crash, and give the following:

E/getTrackerSettings inside try |: false
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sendiman.manager, PID: 13196
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BOOLEAN at line 1 column 6 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
    at com.google.gson.Gson.fromJson(Gson.java:932)
    at com.google.gson.Gson.fromJson(Gson.java:897)
    at com.google.gson.Gson.fromJson(Gson.java:846)

As you can see, this does no make sense. The entire function is inside a larger try catch( Exception e) as well.

CodePudding user response:

The fromJson method throws a com.google.json.JsonSyntaxException. It does not throw a java.lang.IllegalStateException. You're catching the wrong thing.

The text highlights why the JSON is bad, and that IllegalStateException came up as part of parsing it. It's a causal relationship. Think of exceptions not as 'this specific thing went wrong', but as an alternate return value. The fromJson call returns either a T object (the thing you're trying to parse), OR a JsonSyntaxException, and that JsonSyntaxException object (exceptions are just objects) contains the details. You can query it by assigning it to a variable, and its toString also just prints the details. 'some inner parsing code threw an IllegalStateException' is the detail here.

It looks like you're attempting to parse the string "true" or "false" as json. It's not valid JSON, in the sense that all JSON has to be a JSON object in its outermost level.

Replace catch (IllegalStateException) with catch (JsonSyntaxException) instead.

CodePudding user response:

luk2302 Answered in comments.

Catch (JsonSyntaxException e)did catch the crash.

CodePudding user response:

It still fail because you are trying to catch IllegalStateException and not JsonSyntaxException

From javadoc documentation the signature of fromJson is:

public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException

try {
     Log.e("getTrackerSettings | ", json);
     trackerSettings = new Gson().fromJson(json, typeToken);
} catch (JsonSyntaxException e) {
     Log.e("getTrackerSettings inside catch | ", "");
     e.printStackTrace();
     trackerSettings = new TrackerSettings(1, "Hello", "73");
}
  • Related