Java OCA OCP Practice Question 2466

Question

Which lines of code, when inserted at //INSERT CODE HERE,

will enable class Copy to copy contents from file ejava.txt to ejava-copy.txt?

class Copy {/*w w  w .j  a va2 s .com*/
    public static void main(String args[]) {
        try {
            InputStream fis = new DataInputStream(new FileInputStream(
                                             new File("eJava.txt")));
            OutputStream fos = new DataOutputStream(new FileOutputStream(
                                             new File("eJava-copy.txt")));
            int data = 0;
            while ((data = fis.read()) != -1) {
                fos.write(data);
            }
        }
        //catch (/* INSERT CODE HERE */) {
        }
        finally {
            try {
                if (fos != null) fos.close();
                if (fis != null) fis.close();
            }
            catch (IOException e) {}
        }
    }
}
  • a catch (IOException e) {
  • b catch (FileNotFoundException e) {
  • c catch (FileNotFoundException | IOException e) {
  • d catch (IOException | FileNotFoundException e) {


a

Note

Code in class Copy can throw two checked exceptions: FileNotFoundException and IOException.

Instantiation of FileInputStream and FileOutputStream can throw a FileNotFoundException.

Calling methods read() and write() can throw an IOException.

Because IOException is the base class of FileNotFoundException, the exception handler for IOException will handle FileNotFoundException also.

Option (b) won't handle the IOException thrown by methods read() and write().

Options (c) and (d) are incorrect because alternatives in a multi-catch statement must not pass the IS-A test.

The alternatives used in these options pass the IS-A test; FileNotFoundException extends IOException.




PreviousNext

Related