M. *_*awy 3 java exception-handling try-catch return-value
为什么即使抛出异常,以下代码也始终返回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;
}
}
Run Code Online (Sandbox Code Playgroud)
第01版
这是我用来测试前面代码的代码:
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!" );
}
Run Code Online (Sandbox Code Playgroud)
我不认为你看到你认为你所看到的.换句话说,我很确定它实际上是返回false,你应该检查调用代码.
例如,我将您的代码粘贴到一个新的Java控制台应用程序中,使其成为静态,并使用此主体编写一个main方法:
System.out.println(write(null, null));
Run Code Online (Sandbox Code Playgroud)
输出是:
Exception is :
null
false
Run Code Online (Sandbox Code Playgroud)