Home > Net >  Java: How to go about return values in a try-catch?
Java: How to go about return values in a try-catch?

Time:10-02

I am somewhat in doubt about how to go about returning a value in a catch-block, when I really don't want the catch-block to return a value at all.

I am trying to make a java class 'User', that has a method for creating a user account and saving it to a json file, like so:

private void saveAsJson() {
    JSONObject newUser = new JSONObject();
    newUser.put("name", this.name);
    newUser.put("lastName", this.lastName);
    newUser.put("password", this.password);
    System.out.println(newUser);

    try {
        File jsonFile = new File("./data/Account.json");
        fileIsEmpty(jsonFile); //void method checking if file is empty or already contains data.
        getJsonArray(jsonFile);//method that should parse the contents of the jsonfile to a JSONArray.
        
        //More code...
        ///

...

private JSONArray getJsonArray(File sourceFile) {
    try {
        FileReader fr = new FileReader(sourceFile);
        JSONTokener tk = new JSONTokener(fr);
        JSONObject jsonObj = new JSONObject(tk);
        JSONArray jsonArr = jsonObj.getJSONArray("Accounts");
        return jsonArr;
    } catch (Exception e) {
        System.out.println("Unable to read accounts in getJsonArray.");
        return *what to return??*;
    }
}

The Method JSONArray is simply meant to read the json file, and return the array. The FileReader class demands that I use a try-catch, in case an exception happens while trying to read the file. However, when that exception would happen, I don't want the method to return anything at all. The method is already called in a try-block, so I would want this parent try-block to handle the exception, in stead of carrying on with a return value from the method.

How should I go about this. What sort of value should I return? Something like JSONArray fakeArray = new JSONArray(); return fakeArray;? What happens when that value is returned, does saveAsJson() carry on with that empty array, and mess up the structure of my json file?

To be clear: I do understand that and why there must be a return value. The method getJsonArray simply expects a JSONArray to be returned. I do not know how to best handle this.

CodePudding user response:

Don't catch the Exception. Declare that the method throws instead and have the caller of the method catch it.

// It's better to declare the specific type of the Exception instead of bare Exception
private JSONArray getJsonArray(File sourceFile) throws Exception {
    FileReader fr = new FileReader(sourceFile);
    JSONTokener tk = new JSONTokener(fr);
    JSONObject jsonObj = new JSONObject(tk);
    JSONArray jsonArr = jsonObj.getJSONArray("Accounts");
    return jsonArr;
}
  • Related