繁体   English   中英

Java:如何在try-catch中获取go的返回值?

[英]Java: How to go about return values in a try-catch?

当我真的根本不希望 catch 块返回值时,我对如何在 catch 块中返回值 go 有点怀疑。

我正在尝试制作一个 java class“用户”,它有一种创建用户帐户并将其保存到 json 文件的方法,如下所示:

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??*;
    }
}

方法 JSONArray 只是为了读取 json 文件,并返回数组。 FileReader class 要求我使用 try-catch,以防在尝试读取文件时发生异常。 但是,当发生该异常时,我根本不希望该方法返回任何内容。 该方法已在 try 块中调用,因此我希望此父 try 块处理异常,而不是继续使用该方法的返回值。

我应该怎么go一下这个。 我应该返回什么样的价值? 类似于JSONArray fakeArray = new JSONArray(); return fakeArray; JSONArray fakeArray = new JSONArray(); return fakeArray; 返回该值时会发生什么,saveAsJson() 是否继续处理该空数组,并弄乱我的 json 文件的结构?

明确一点:我确实理解这一点以及为什么必须有返回值。 方法 getJsonArray 只是期望返回一个 JSONArray。 我不知道如何最好地处理这个问题。

不要捕获Exception 声明该方法改为throws并让方法的调用者捕获它。

// 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM