1

I am developing a project which involves JSON manipulation in Java using JSON API. There are many places where I need to read values from JSON file. The API provides checked exceptions for the same. Everytime I use the API to read JSON values, I am forced to write try catch block. As a result, there is a large number of try catch blocks. It makes the code look messy.

    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();
    }

Is there any way to avoid this ?A single try catch block would not suffice and the statements are not dependent. Each read statement requires a separate try catch block as I have to log the details of places while catching the exception. Can I invoke a common method whenever I have a code to read JSON data, like sending the code as a paramater to a method which would take care of the exception handling or some other way round ?

3
  • Why catch these exceptions at all? Just let them bubble up. Commented Oct 28, 2015 at 7:19
  • You could also have one big try/catch block with everything inside. Commented Oct 28, 2015 at 7:20
  • 2
    You should not have separate try/catch like this... Anyway if your first try fails, all the others are bound to fail too since read would be null... Commented Oct 28, 2015 at 7:20

3 Answers 3

1

Since (all?) the subsequent statements are dependent on the previous it makes no sense having that many try/catch blocks. I would rather put the code inside one try/catch and handle the exceptions by type

Pseudo-code:

 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

As some are suggesting, you might want to let all these exceptions bubble up (not catching them) since you're not doing anything meaningful when catching them. However, I think that depends on the calling context.

Sign up to request clarification or add additional context in comments.

9 Comments

I would rather have separate catch blocks. Don't rely on instanceOf, it can cause chaos in case of inheritance
The premise is correct but your catch statement is no good, before I downvote I would like to give you the opportunity to fix it. You should catch those in their own catch block.
@VinodMadyalkar: Well, inheritence will work just the same way in multiple catch blocks.
@Thilo - Right. I was just making a general note about not relying in instanceOf too much in situations like this. Of course if the ordering of catch blocks is wrong, the OP will get an Unreachable code compiler error :)
I am with @ug_, don't catch these exceptions at all, let them bubble up. Only catch exceptions when you can really do something about them.
|
0

If you are handling all exceptions in the same way, why not combine them in one try/ catch clause for example like this :

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 Comments

and that also allows you to declare content and responseArr locally inside that scope.
catch (Exception e) is not a good idea in the most cases. Try to be more specific since your statement will also catch RuntimeExceptions
0

Try like this

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");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.