Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium

Question 73

Question ID: UKOCP54104


Given Code:


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:

  • E

    Surround Line n4 with below try-catch block:

  • F

    Surround Line n4 with below try-catch block:

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:

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need