【发布时间】:2018-04-05 14:33:08
【问题描述】:
我对使用 throws 的 try/catch 感到困惑。我在一个函数中有两个可能的 IOExceptions。一,我想抓住并继续。另一个我想抛出一个异常给前面的函数处理。
如果 IOException 无法打开文件,我想捕获它,通知用户并继续。如果清除目录时出现IOException,我想在调用代码中抛出异常并处理。
如果无法打开文件,它会抛出 clearUploads() 在捕获异常时可能抛出的异常吗?
主要:
output = parseCSV(fileList);
功能:
private static String parseCSV(List<File> fileList) throws IOException {
String returnString = "";
String[] tokens = null;
String currFileName = "";
for(File file: fileList){
currFileName = file.getName();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
}
//do stuff
}
br.close();
} catch (FileNotFoundException e) {
returnString += "Cannot find " + currfileName + "!\n";
} catch (IOException e) {
returnString += "Cannot open " + currFileName + "!\n";
}
}
clearUploads();
if (returnString.equals("")) {
returnString = "Files uploaded and saved successfully";
}
return returnString;
}
private static void clearUploads() throws IOException {
FileUtils.cleanDirectory(new File(filePath));
}
【问题讨论】:
-
如果无法打开文件,它会抛出 clearUploads() 在捕获异常时可能抛出的异常吗? 是。下一个问题。
-
@ElliottFrisch 你真的看到 clearUploads() 周围的 try catch 块吗?不,它不会,它不在实现的块的范围内。下一个不称职的评论。
-
@apexlol 嗯?它肯定会从 clearUploads 抛出相同的异常(因为它不处理异常)。我对 try catch 块只字未提。 clearUploads 不在 try-catch 块中。
-
您的
br.close()也不安全。您应该在finally中调用它,或者最好使用 try-with-resources。
标签: java