gpt4 book ai didi

java - 为什么 catch block 中的 Java return 语句不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:44 24 4
gpt4 key购买 nike

为什么下面的代码在抛出异常时总是返回true?

public boolean write (ArrayList<String> inputText, String locationToSave){

try {
File fileDir = new File(locationToSave);
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir), "utf8"));

int index = 0;
int size = inputText.size();
while (index < size) {
out.append(inputText.get(index));
out.append("\n");
index++;
}
out.flush();
out.close();

return true;

} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException is : \n" + e.getMessage());
return false;
} catch (IOException e) {
System.out.println("IOException is : \n" + e.getMessage());
return false;
} catch (Exception e) {
System.out.println("Exception is : \n" + e.getMessage());
return false;
}
}

第 1 版

这是我用来测试之前代码的代码:

 if (fileReader.write(fileReader.read(selectedFile), selectedSaveLocation)) {
System.out.println("The file : " + selectedFile + " as been successfully"
+ "converted to : " + selectedSaveLocation );
} else {
System.out.println("The file : " + selectedFile + " failed to convert!" );
}

最佳答案

我不认为您看到了您认为看到的东西。换句话说,我很确定它实际上返回了 false,您应该检查调用代码。

例如,我将您的代码粘贴到一个新的 Java 控制台应用程序中,使其成为静态的,并用这个主体编写了一个 main 方法:

System.out.println(write(null, null)); 

输出是:

Exception is : 
null
false

关于java - 为什么 catch block 中的 Java return 语句不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2280050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com