1

我正在开发一个项目,该项目涉及使用JSON API在 Java 中进行 JSON 操作。有很多地方我需要从 JSON 文件中读取值。API 提供了相同的检查异常。每次我使用 API 读取 JSON 值时,我都被迫编写 try catch 块。结果,有大量的try catch块。它使代码看起来很混乱。

    String Content = "";
    try {
        read = new BufferedReader(new FileReader("Data.json"));
    }
    catch(Exception e) {
        System.out.println("File Not found");
    }

    try {
        while((line = read.readLine() ) != null) { 
            Content = Content+line;     
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        ResponseArr = new JSONArray( Content );
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");

    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        StoreResponse = ResponseArr.getJSONObject(0).getJSONArray("childrens");

    } catch (JSONException e) {
        e.printStackTrace();
    }

有什么方法可以避免这种情况吗?单个 try catch 块是不够的,并且语句不依赖。每个读取语句都需要一个单独的 try catch 块,因为我必须在捕获异常时记录位置的详细信息。每当我有读取 JSON 数据的代码时,我是否可以调用一个通用方法,例如将代码作为参数发送给一个负责异常处理或其他方式的方法?

4

3 回答 3

1

由于(全部?)后续语句依赖于前面的语句,因此拥有那么多 try/catch 块是没有意义的。我宁愿将代码放在一个 try/catch 中并按类型处理异常

伪代码:

 String Content = "";
    try {
        read = new BufferedReader(new FileReader("Data.json"));
        while((line = read.readLine() ) != null) { 
            Content = Content+line;     
        }
        ResponseArr = new JSONArray( Content );
        ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
    } catch (JSONException e) {       
        e.printStackTrace();    
    } catch(FileNotFoundException)
            System.out.println("File Not found");
    }
    // and so on

正如一些人建议的那样,您可能希望让所有这些异常冒泡(而不是捕获它们),因为在捕获它们时您没有做任何有意义的事情。但是,我认为这取决于调用上下文。

于 2015-10-28T07:22:09.370 回答
0

如果您以相同的方式处理所有异常,为什么不将它们组合在一个 try/catch 子句中,例如:

try {
        while((line = read.readLine() ) != null) { 
            Content = Content+line;     
        }
       ResponseArr = new JSONArray( Content );
       ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
    } catch (Exception e) {
        e.printStackTrace();
    }
于 2015-10-28T07:24:41.390 回答
0

像这样试试

String Content = "";
try {
    read = new BufferedReader(new FileReader("Data.json"));
       while((line = read.readLine() ) != null) { 
        Content = Content+line;     
      }
      ResponseArr = new JSONArray( Content );
      ResponseObj = ResponseArr.getJSONObject(1).getJSONArray("childrens");
    } 
    catch (IOException e) {
      e.printStackTrace();
    }
    catch (JSONException e) {
      e.printStackTrace();
    }
    catch(Exception e) {
      System.out.println("File Not found");
    }
于 2015-10-28T07:31:35.730 回答