首页 > 解决方案 > 在 for-each 循环中捕获引发异常的确切项目

问题描述

我需要访问我的子句中的File变量。我怎样才能做到这一点?fcatch

try { 
    for(File f:filesInDir) {
        new Scanner(new FileInputStream(f)); 
} 
catch(FileNotFoundException e) { 
    System.out.println("Could not open input file "+ f +" for reading.");
}

标签: javaexception

解决方案


Try placing the try/catch block in you for loop like this:

for(File f : filesInDir) {
  try {
    new Scanner(new FileInputStream(f));
  } catch (FileNotFoundException e) {
    System.out.println("Could not open input file " + f + " for reading.");
  } 
}

推荐阅读