Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly handle important unchecked exceptions

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?

like image 434
Mike Avatar asked Feb 26 '12 17:02

Mike


People also ask

How do you handle unchecked exceptions?

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.

Is it good practice to handle unchecked exceptions?

Programmers should properly handle unchecked exceptions when they are expected and are not caused by programming errors.

What happens when unchecked exception is thrown?

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.


1 Answers

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();
}
like image 146
Jeffrey Avatar answered Oct 05 '22 23:10

Jeffrey