I'm writing a library that wraps around a REST API. The wrapper I'm creating uses GSON to deserialize the json into my object. Basically, something like this...
public Post getPost(url) throws IOException {
String jsonString = httpClient.get(url);
Post p = gson.fromJson(jsonString, Post.class);
// return Post to client and let client do something with it.
}
If I understand correctly, IOException is a checked exception. I'm telling my client: Hey, buddy - you better watch out and recover from this exception. Now my client can wrap the call in a try/catch and determine what to do if there is some network failure.
The GSON fromJson() method throws a JsonSyntaxException. I believe this is unchecked in the Java world, as one of its super classes is RuntimeException, and also because I am not required to add a try/catch or another "throws" like IOException.
Assuming what I have said so far is correct - how exactly should the API and client handle this situation? If the json string is garbage, my client is going to fail miserably due to the JsonSyntaxException because it's unchecked.
// Client
PostService postService = new PostService();
try{
Post p = postService.getPost(urlString);
// do something with post
}catch (IOException){
// handle exception
}
// ok, what about a JsonSyntaxException????
What's the best way to handle these situations?
A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.
Programmers should properly handle unchecked exceptions when they are expected and are not caused by programming errors.
If a program throws an unchecked exception, it reflects some error inside the program logic. Java does not verify unchecked exceptions at compile-time. Furthermore, we don't have to declare unchecked exceptions in a method with the throws keyword.
You are allowed to catch unchecked exceptions. Just add catch(JsonSyntaxException e)
to your try-catch block. After you catch the JsonSyntaxException
, you can either handle it or rethrow it as a checked exception.
Ex:
try{
//do whatever
}catch(JsonSyntaxException e){
e.printStackTrace();
// throw new Exception(e); //checked exception
}catch(IOException e){
e.printStackTrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With