Which code fragments, when inserted independently at line **, enable the code to compile?

Given the code fragment:
<code>
private static void copyContents (File source, File target) {
try {inputStream fis = new FileInputStream(source);
outputStream fos = new FileOutputStream (target);
byte [] buf = new byte [8192];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write (buf, 0, i);
}
//insert code fragment here. Line **
System.out.println (“Successfully copied”);
}
</code>
Which code fragments, when inserted independently at line **, enable the code to compile?

Given the code fragment:

private static void copyContents (File source, File target) {
try {inputStream fis = new FileInputStream(source);
outputStream fos = new FileOutputStream (target);
byte [] buf = new byte [8192];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write (buf, 0, i);
}
//insert code fragment here. Line **
System.out.println ("Successfully copied");
}

Which code fragments, when inserted independently at line **, enable the code to compile?

A.
}catch (IOException | NoSuchFileException e) {
System.out.println(e);
}

B.
} catch (IOException | IndexOutOfBoundException e) {
System.out.println(e);
}

C.
} catch (Exception | IOException | FileNotFoundException e ) {
System.out.println(e);
}

D.
} catch (NoSuchFileException e ) {
System.out.println(e);
}

E.
} catch (InvalidPathException | IOException e) {
System.out.println(e);
}

Explanation:
B: Two mutually exclusive exceptions. Will work fine.
D: A single exception. Will work fine.
E: Two mutually exclusive exceptions. Will work fine.
Note: In Java SE 7 and later, a single catch block can handle more than one type of exception.
This feature can reduce code duplication and lessen the temptation to catch an overly broad
exception.
In the catch clause, specify the types of exceptions that block can handle, and separate each
exception type with a vertical bar (|).
Note 2:NoSuchFileException: Checked exception thrown when an attempt is made to access a file
that does not exist.
InvalidPathException: Unchecked exception thrown when path string cannot be converted into
a Path because the path string contains invalid characters, or the path string is invalid for other file
system specific reasons.
FileNotFoundException: Signals that an attempt to open the file denoted by a specified pathname
has failed.
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile
constructors when a file with the specified pathname does not exist. It will also be thrown by these
constructors if the file does exist but for some reason is inaccessible, for example when an attempt
is made to open a read-only file for writing.



Leave a Reply 2

Your email address will not be published. Required fields are marked *


zzZZzzzzZZzzz

zzZZzzzzZZzzz

B,E

thiago

thiago

if you insert the letter D, the code don’t compile, because none of the constructor or methods can raise this exception