Java:如何在try-catch中返回值



当我真的不想让catch块返回值时,我有点怀疑如何在catch块中返回值。

我正在尝试创建一个java类"User",它有一个创建用户帐户并将其保存到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类要求我使用try-catch,以防在尝试读取文件时发生异常。但是,当发生异常时,我根本不希望该方法返回任何内容。该方法已经在try块中被调用,所以我希望这个父try块处理异常,而不是继续使用该方法的返回值。

我该怎么办。我应该返回什么样的值?类似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;
}

最新更新