Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Try Catch in Java | Json still crashes

                 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading