I am trying to catch an error of type MalformedJsonException from gson library version 2.8.5.
try {
String json = "{ \"name\": \"prueba\", \"java\": true}}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
System.out.println(jsonObject.get("name"));
}catch(MalformedJsonException e)
{
System.out.println(e.getMessage());
}
The problem is that when I try to use the MalformedJsonException class as a catch I get the following error.
Unreachable catch block for MalformedJsonException. This exception is never thrown from the try statement body.
Is there a way to catch this type of error when they have this problem?
The exception you have to catch is
JsonSyntaxException
This exception is the one that throws the parse method (among other methods) to indicate that the JSON is not valid:
You can also control with the setLenient method of JsonReader how strict you want that JSON to be parsed:
The compiler isn't forcing you to catch it because this class inherits from RuntimeException, but you can (and should) catch it to deal with the case of malformed JSON.
The block
catch
has to catch exceptions that are thrown inside the blocktry
, it cannot catch an exception that your code is not throwing.And you are trying to catch an exception that is never thrown in your try code block:
Indeed,
.parse()
he does not throw the exceptionMalformedJsonException
as @Ordago comments, you can see the exception that really needs to be caught in his response: Ordago's responseOriginal Answer on SO from User Christian