【问题标题】:Try/Catch with Throws尝试/接球
【发布时间】: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


【解决方案1】:

try 块将捕获它在其范围内并且与 catch 部分中的类型兼容的任何内容,因为 clearUploads 在 try 块之外,它不会被该块特别捕获。

【讨论】:

  • 谢谢。一个愚蠢的问题,我知道,但我宁愿确定也不要困惑。
  • 在 SO 中提问之前尝试查看文档,大多数情况下可能需要更长的时间,但您会学到更多。 try,scope
猜你喜欢
  • 1970-01-01
  • 2016-05-11
  • 2018-07-17
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多