在Java中避免使用相同的try catch块

时间:2015-10-28 07:12:58

标签: java json exception-handling org.json

我正在使用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块是不够的,而且语句不依赖。每个read语句都需要一个单独的try catch块,因为我必须在捕获异常时记录位置的详细信息。每当我有一个读取JSON数据的代码时,我可以调用一个公共方法,比如将代码作为参数发送到一个方法来处理异常处理或其他方式吗?

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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();
    }

答案 2 :(得分: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");
    }
相关问题