How to handle important unchecked exceptions correctly

I am writing a library that wraps around the REST API. The created shell uses GSON to deserialize 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, an IOException is a checked exception. I tell my client: Hey buddy, itโ€™s better to watch and recover from this exception. Now my client can wrap the call in try / catch and determine what to do if there is a network failure.

The GSON fromJson () method throws a JsonSyntaxException. I believe this is not tested in the Java world, because one of its superclasses is a RuntimeException, and also because I donโ€™t need to add try / catch or other โ€œthrowsโ€ like IOException.

Assuming what I said so far, itโ€™s right - exactly how the API and client should deal with this situation? If the json string is garbage, my client will fail due to a JsonSyntaxException exception because it is not installed.

 // 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 is the best way to deal with these situations?

+6
source share
1 answer

You are allowed to exclude uncontrolled exceptions. Just add catch(JsonSyntaxException e) to the try-catch block. After you catch a JsonSyntaxException , you can either handle it or reset it as a checked exception.

Example:

 try{ //do whatever }catch(JsonSyntaxException e){ e.printStackTrace(); // throw new Exception(e); //checked exception }catch(IOException e){ e.printStackTrace(); } 
+6
source

Source: https://habr.com/ru/post/909399/


All Articles