user11221895
user11221895

Reputation: 7

Catch exact item that throws Exception in a for-each loop

I need access to the File variable f inside my catch clause. How can I achieve this?

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

Upvotes: 1

Views: 49

Answers (2)

Don Brody
Don Brody

Reputation: 1727

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.");
  } 
}

Upvotes: 1

Ali Nasim
Ali Nasim

Reputation: 111

You can print the exception by e in the catch block..Along with that, it has lot of methods which is going to be useful if you do CTRL + SPACE.. Hope it helps..

Upvotes: 0

Related Questions