Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 57
Question ID: UKOCP61623
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.io.IOException;
- import java.sql.SQLException;
- class MyResource implements AutoCloseable {
- @Override
- public void close() throws IOException{
- throw new IOException("IOException");
- }
- public void execute() throws SQLException {
- throw new SQLException("SQLException");
- }
- }
- public class Test {
- public static void main(String[] args) {
- try(MyResource resource = new MyResource()) {
- resource.execute();
- } catch(Exception e) {
- System.out.println(e.getSuppressed()[0].getMessage());
- }
- }
- }
What will be the result of compiling and executing Test class?
- A IOException
- B SQLException
- C Compilation error
Reveal correct answer
Correct answer: A
Explanation
UKOCP61623:
execute() method throws an instance of SQLException.
Just before finding the matching handler, Java runtime executes close() method. This method throws an instance of IOException but it gets suppressed and an instance of SQLException is thrown.
e.getSuppressed() returns Throwable [] whose 1st element is the instance of suppressed exception, IOException.
'e.getSuppressed()[0].getMessage()' prints IOException on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
