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

Mik*_*ike 6 java exception-handling gson

我正在编写一个包装REST API的库.我正在创建的包装器使用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.
}
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,IOException是一个经过检查的异常.我告诉我的客户:嘿,伙计 - 你最好注意并从这个例外中恢复过来.现在我的客户端可以在try/catch中包装调用,并确定在出现网络故障时该怎么做.

GSON fromJson()方法抛出JsonSyntaxException.我相信这在Java世界中是未经检查的,因为它的一个超类是RuntimeException,而且因为我不需要添加try/catch或像IOException这样的"throws".

假设我到目前为止所说的是正确的 - 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????
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*rey 6

您可以捕获未经检查的异常.只需添加catch(JsonSyntaxException e)到try-catch块即可.捕获后JsonSyntaxException,您可以处理它或将其重新抛出为已检查的异常.

例如:

try{
    //do whatever
}catch(JsonSyntaxException e){
    e.printStackTrace();
    // throw new Exception(e); //checked exception
}catch(IOException e){
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)