OCP Exception Handling and Assertions Questions and Answers 1 — Questions and Answers
Question 1: Examine the following code which uses a try-with-resources statement. What is the output when this code is executed? ```java class Door implements AutoCloseable { private String name; public Door(String name) { this.name = name; System.out.println(name + " opened"); } @Override public void close() { System.out.println(name + " closed"); } } public class Test { public static void main(String[] args) { try (Door front = new Door("Front"); Door back = new Door("Back")) { System.out.println("Walking through doors"); } } } ```
- Front opened Back opened Walking through doors Front closed Back closed
- Front opened Back opened Walking through doors Back closed Front closed (Correct answer)
- Front opened Walking through doors Front closed Back opened Back closed
- The code will not compile because multiple resources are declared.
Correct answer: Front opened Back opened Walking through doors Back closed Front closed
In a try-with-resources statement, resources are initialized in the order they are declared. However, they are closed in the reverse order of their declaration. Therefore, 'Front' is opened first, then 'Back'. After the try block executes, 'Back' is closed first, and then 'Front' is closed.
Question 2: What is the final value returned by the `checkValue` method when executed? ```java public class Test { public static int checkValue() { try { System.out.println("Executing try"); return 10; } catch (Exception e) { System.out.println("Executing catch"); return 20; } finally { System.out.println("Executing finally"); return 30; } } public static void main(String[] args) { System.out.println("Returned: " + checkValue()); } } ```
- 20
- 10
- 30 (Correct answer)
- The code will not compile because a `finally` block cannot have a `return` statement.
Correct answer: 30
The `finally` block is always executed after the `try` block exits. If a `finally` block includes a `return` statement, it will override any value that was about to be returned from the `try` or `catch` block. In this case, the `try` block prepares to return 10, but the `finally` block executes and its `return` statement overrides the previous one, causing the method to return 30.
Question 3: Which of the following statements about the `assert` keyword in Java is true?
- Assertions are a replacement for standard exception handling for public methods.
- An `AssertionError` is a checked exception that must be caught or declared.
- Assertions are enabled by default and must be disabled with the `-da` flag.
- Assertions can be enabled at runtime using the `-ea` flag and are primarily intended for debugging and testing. (Correct answer)
Correct answer: Assertions can be enabled at runtime using the `-ea` flag and are primarily intended for debugging and testing.
Assertions are disabled by default and are not meant to replace standard exception handling. They are intended for developers to verify internal invariants during development and testing. They can be enabled with the JVM flag `-ea` or `-enableassertions`. If an assertion fails, it throws an `AssertionError`, which is a subclass of `Error` (an unchecked throwable), not a checked exception.
Question 4: A method is declared to throw both `java.io.IOException` and `java.sql.SQLException`. Which of the following `catch` clauses is the correct and most concise way to handle both of these distinct exception types in a single block?
- ```java catch (IOException e1, SQLException e2) { /* ... */ } ```
- ```java catch (Exception e) { /* ... */ } ```
- ```java catch (IOException & SQLException e) { /* ... */ } ```
- ```java catch (IOException | SQLException e) { /* ... */ } ``` (Correct answer)
Correct answer: ```java catch (IOException | SQLException e) { /* ... */ } ```
Since Java 7, a single `catch` block can handle multiple exception types using the multi-catch syntax, which separates the exception types with a single vertical bar `|`. The exception variable (`e` in this case) is implicitly final. While catching the superclass `Exception` would also work, it is less specific and therefore not the *best* answer for handling only these two specific types.
Question 5: Which of the following exceptions is a checked exception that the Java compiler requires to be handled or declared?
- NullPointerException
- java.io.FileNotFoundException (Correct answer)
- ArrayIndexOutOfBoundsException
- ClassCastException
Correct answer: java.io.FileNotFoundException
`FileNotFoundException` is a subclass of `IOException`, which is a checked exception. The Java compiler enforces that checked exceptions must be either caught in a try-catch block or declared in the method signature with a `throws` clause. The other options (`NullPointerException`, `ArrayIndexOutOfBoundsException`, `ClassCastException`) are all subclasses of `RuntimeException` and are therefore unchecked exceptions.
Question 6: Consider a `try-with-resources` statement. If an exception is thrown within the `try` block, and a different exception is thrown when the resource's `close()` method is automatically called, what happens?
- The exception from the `try` block is thrown, and the exception from the `close()` method is added to it as a suppressed exception. (Correct answer)
- Only the exception from the `close()` method is thrown, as it occurs last.
- The program terminates immediately without throwing any specific exception.
- Both exceptions are thrown, and the calling method must have two separate `catch` blocks to handle them.
Correct answer: The exception from the `try` block is thrown, and the exception from the `close()` method is added to it as a suppressed exception.
In a `try-with-resources` block, if an exception occurs in the `try` block (the primary exception) and another occurs during the automatic closing of a resource, the second exception is suppressed. The primary exception is the one that is propagated up the call stack. The suppressed exception is attached to the primary one and can be retrieved by calling the `getSuppressed()` method on the primary exception object.
Examine the following code which uses a try-with-resources statement.
What is the output when this code is executed?
```java
class Door implements AutoCloseable {
private String name;
public Door(String name) { this.name = name; System.out.println(name + " opened"); }
@Override
public void close() { System.out.println(name + " closed"); }
}
public class Test {
public static void main(String[] args) {
try (Door front = new Door("Front"); Door back = new Door("Back")) {
System.out.println("Walking through doors");
}
}
}
```