Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 73
Question ID: UKOCP54104
Given Code:
- import java.io.*;
- class ReadTheFile {
- static void print() { //Line n1
- throw new IOException(); //Line n2
- }
- }
- public class Test {
- public static void main(String[] args) { //Line n3
- ReadTheFile.print(); //Line n4
- }
- }
Which 2 changes are necessary so that code compiles successfully?
-
A
Replace Line n1 with
static void print() throws Exception { -
B
Replace Line n1 with
static void print() throws Throwable { -
C
Replace Line n3 with
public static void main(String[] args) throws IOException { -
D
Surround Line n4 with below try-catch block:
- try {
- ReadTheFile.print();
- } catch(IOException e) {
- e.printStackTrace();
- }
-
E
Surround Line n4 with below try-catch block:
- try {
- ReadTheFile.print();
- } catch(IOException | Exception e) {
- e.printStackTrace();
- }
-
F
Surround Line n4 with below try-catch block:
- try {
- ReadTheFile.print();
- } catch(Exception e) {
- e.printStackTrace();
- }
Reveal correct answers
Correct answers: A, F
Explanation
UKOCP54104:
This question is tricky as 2 changes are related and not independent. Let's first check the reason for compilation error. Line n2 throws a checked exception, IOException but it is not declared in the throws clause. So, print method should have throws clause for IOException or the classes in top hierarchy such as Exception or Throwable.
Based on this deduction, Line n1 can be replaced with either "static void print() throws Exception {" or "static void print() throws Throwable" but we will have to select one out of these as after replacing Line n1, Line n4 will start giving error as we are not handling the checked exception at Line n4.
This part is easy, do we have other options, which mention "Throwable"? NO. Then mark the first option as "Replace Line n1 with static void print() throws Exception {".
As, print() method throws Exception, so main method should handle Exception or its super type and not it's subtype. Two options working only with IOException can be ruled out.
Multi-catch statement "catch(IOException | Exception e)" causes compilation error as IOException and Exception are related to each other in multilevel inheritance. So you are left with only one option to pair with the 1st choice:
Surround Line n4 with below try-catch block:
- try {
- ReadTheFile.print();
- } catch(Exception e) {
- e.printStackTrace();
- }
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
