Code: Select all
public class FileCopier {
public static void copy(String records1, String records2) {
try {InputStream is = new FileInputStream(records1);
OutputStream os = new FileOutputStream(records2);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
System.out.println("Read and written bytes " + bytesRead);
}
} catch (FileNotFoundException | IndexOutOfBoundsException e) { e.printStackTrace(); } }
public static void main(String[] args) {
copy("c:\\temp\\test1.txt", "c:\\temp\\test2.txt");
}
}
Assuming appropriate import statements and the existence of both the files, what will happen when the program is compiled and run?
The problem is. I am not agree with explanation for the right answer.
Answer is this: The program will not compile because it does not handle exceptions correctly.
Explanation: Remember that most of the I/O operations (such as opening a stream on a file, reading or writing from/to a file) throw IOException and this code does not handle IOException. FileNotFoundException is a subclass of IOException and IndexOutOfBoundsException is subclass of RuntimeException. The code can be fixed by replacing both the exceptions with IOException.
The first part is fine, catch clause doesn't handle the IOException, so by replacing just FileNotFoundException with IOException will compile and run just fine! Why do we need to replace BOTH exceptions with IOException? and not just first one? More ... if we replace BOTH the exceptions with IOException the code will not compile.
Please correct me if it was misunderstanding.