'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.
Solution 1:[1]
luk2302 Answered in comments.
Catch (JsonSyntaxException e)did catch the crash.
Solution 2:[2]
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");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roey Michaeli |
| Solution 2 | omer blechman |
