Java 如何正确处理重要的未检查异常

Java 如何正确处理重要的未检查异常,java,exception-handling,gson,Java,Exception Handling,Gson,我正在编写一个围绕RESTAPI的库。我正在创建的包装器使用GSON将json反序列化到我的对象中。基本上是这样的 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 somethin

我正在编写一个围绕RESTAPI的库。我正在创建的包装器使用GSON将json反序列化到我的对象中。基本上是这样的

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.
}
如果我理解正确,IOException是一个选中的异常。我告诉我的客户:嘿,伙计,你最好小心点,从这个异常中恢复过来。现在,我的客户机可以将调用包装为try/catch,并确定如果出现网络故障该怎么办

GSON fromJson()方法抛出一个JsonSyntaxException。我相信这在Java世界中是未经检查的,因为它的一个超类是RuntimeException,而且也因为我不需要添加try/catch或其他类似IOException的“抛出”

假设到目前为止我所说的是正确的,那么API和客户端应该如何处理这种情况呢?如果json字符串是垃圾,我的客户机将由于JsonSyntaxException而失败,因为它未经检查

// Client
PostService postService = new PostService();
try{
  Post p = postService.getPost(urlString);
  // do something with post
}catch (IOException){
   // handle exception
}
// ok, what about a JsonSyntaxException????

处理这些情况的最佳方法是什么?

您可以捕获未检查的异常。只需将
catch(JsonSyntaxException e)
添加到try-catch块。捕获
JsonSyntaxException
后,您可以处理它,也可以将其作为选中的异常重新播放

例:


这在客户端代码中吗?如果是这样,客户端如何知道可以抛出JsonSyntaxException?@CodeBlue这可能在客户端代码中(他们会知道可以抛出它,因为API可能指定可以抛出它),也可能在
getPost
方法中。如果它在
getPost
方法中,您将无法捕获
IOException
,您将把
JsonSyntaxException
作为选中的异常传递。确定。感谢您的澄清。问题是为什么Json***异常是RuntimeExceptions而不是checked异常?!?
try{
    //do whatever
}catch(JsonSyntaxException e){
    e.printStackTrace();
    // throw new Exception(e); //checked exception
}catch(IOException e){
    e.printStackTrace();
}