Reputation: 5657
Let's say I have a custom reader object that throws exception:
public StationReader {
public StationReader(String inFile) throws FileNotFoundException {
Scanner scan = new Scanner(inFile);
while (scan.hasNextLine() {
// blah blah blah
}
// Finish scanning
scan.close();
}
}
And I call the StationReader in another class, Tester:
public Tester {
public static void main(String[] args) {
try {
StationReader sReader = new StationReader("i_hate_csv.csv");
} catch (FileNotFoundException e) {
System.out.println("File not found arggghhhhhh");
} finally {
// HOW TO CLOSE SCANNER HERE??
}
}
}
Now let's imagine that whilst scanning through the lines, an exception is thrown, so scan.close()
is never called.
How do I close the scanner object then in this case?
Upvotes: 0
Views: 96
Reputation: 347314
Write the read process in a try-with-resources
statement, but don't catch any of the exceptions, simply let them be passed back to the caller, for example...
public class CustomReader {
public CustomReader(String inFile) throws FileNotFoundException {
try (Scanner scan = new Scanner(inFile)) {
while (scan.hasNextLine()) {
// blah blah blah
}
}
}
}
The try-with-resource
statement will automatically close the resource when the code exists the try
block
fyi: finally
use to be used for this, but when you have multiple resources, it becomes messy. All hail try-with-resources
🎉
Upvotes: 4