Handling Exceptions practice questions

From OCP Java SE 8 (1Z0-809) · 21 questions on this topic

Handling Exceptions practice questions from OCP Java SE 8 (1Z0-809). This pack has 21 questions tagged Handling Exceptions, drawn from its timed mock exams. 8 of them are worked through in full below — the question, every option, why each is right or wrong, and the explanation.

Worked examples for Handling Exceptions

  1. Question 1

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { RuntimeException e = new RuntimeException("top"); System.out.println(e.getMessage() + " " + e.getCause()); } } ```

    1. A. top followed by an empty string

      getCause returns null, which concatenation renders as the literal text null, not an empty string.

    2. B. top nullCorrect answer

      Correct: the message is present and the absent cause concatenates as the text null.

    3. C. top top

      The cause is not the message; without a supplied cause it is null.

    4. D. An exception is thrown because the cause was never set

      Building the exception does not require a cause or throw over a missing one.

    Explanation

    Constructing an exception does not throw it; it is ordinary object creation. With no cause supplied, getCause returns null, which string concatenation renders as the text null.

  2. Question 2

    What is the result of compiling the following program? ```java public class Main { static class Res implements AutoCloseable { public void close() { } } public static void main(String[] args) { try (Res r = new Res()) { r = null; System.out.println("body"); } } } ```

    1. A. Compilation failsCorrect answer

      A resource variable is implicitly final, so reassigning r inside the block ("auto-closeable resource r may not be assigned") is a compile error.

    2. B. body, and close is skipped because r is null

      Assumes the reassignment to null is legal and would suppress the close; the reassignment does not compile, and the emitted close operates on the original resource, not the current value of the variable.

    3. C. body

      Assumes the code compiles and runs normally; the illegal reassignment of the implicitly final resource variable prevents compilation, so no output is produced.

    4. D. A NullPointerException is thrown at close time

      Assumes the reassignment compiles and leads to a null close at runtime; the reassignment is rejected at compile time, so no runtime behavior occurs.

    Explanation

    A resource declared in a try-with-resources header is implicitly final, so any attempt to reassign it within the block is a compile error. That implicit finality is exactly what lets the compiler emit a dependable close call on the original resource.

  3. Question 3

    Which statement about the AutoCloseable and Closeable interfaces is correct?

    1. A. Only classes implementing Closeable can be used in try-with-resources

      try-with-resources accepts any AutoCloseable, not only Closeable.

    2. B. Both interfaces declare close() as throwing no checked exceptions

      AutoCloseable's close is declared to throw a checked Exception, so it is not exception-free.

    3. C. AutoCloseable.close() declares throws Exception; Closeable.close() narrows it to IOExceptionCorrect answer

      Correct: AutoCloseable.close throws Exception and Closeable narrows that to IOException.

    4. D. Closeable is the parent interface of AutoCloseable

      The hierarchy is the reverse: AutoCloseable is the parent and Closeable the child.

    Explanation

    AutoCloseable is the broad parent whose close is declared to throw Exception, and Closeable extends it, narrowing the declared exception to IOException. try-with-resources requires only AutoCloseable.

  4. Question 4

    What is the result of compiling the following program? ```java public class Main { public static void main(String[] args) { try { if (args.length == 0) { throw new IllegalStateException(); } throw new IllegalArgumentException(); } catch (IllegalStateException | IllegalArgumentException e) { e = new IllegalArgumentException(); System.out.println("replaced"); } } } ```

    1. A. An exception is thrown at runtime

      Assumes the code compiles and reaches runtime; the illegal assignment to the multi-catch parameter is rejected at compile time, so the program never runs to throw anything.

    2. B. Compilation failsCorrect answer

      A multi-catch parameter is implicitly final, so reassigning it inside the handler ("multi-catch parameter e may not be assigned") is a compile error.

    3. C. replaced

      Assumes the reassignment is legal and the handler runs to print its message; because the multi-catch parameter is implicitly final, the assignment does not compile and nothing is printed.

    4. D. It compiles; the assignment changes the caught exception

      Overlooks that finality depends on the catch form: a single-type catch parameter may be reassigned, but a multi-catch parameter is implicitly final, so this particular assignment is rejected.

    Explanation

    A MULTI-catch parameter is implicitly final — assignment to e is rejected ("multi-catch parameter e may not be assigned"). A single-type catch parameter, by contrast, may be reassigned (bad style, but legal).

  5. Question 5

    What is the output of the following program? ```java public class Main { static class Res implements AutoCloseable { private final String n; Res(String n) { this.n = n; } public void close() { System.out.print(n); } } public static void main(String[] args) { try (Res a = new Res("1"); Res b = new Res("2")) { System.out.print("B"); } System.out.println(); } } ```

    1. A. B21Correct answer

      The body prints B first, then resources close in the reverse of their declaration order, so the second resource (prints 2) closes before the first (prints 1), giving B21. A try-with-resources needs neither catch nor finally.

    2. B. B12

      Assumes resources close in declaration order (first then second); the closing order is reversed, not forward.

    3. C. 12B

      Assumes the resources close before the body runs; the implicit close happens after the block body completes, not before it.

    4. D. Compilation fails because there is no catch or finally

      Believes a try requires a catch or finally clause; a try-with-resources statement is complete on its own because the implicit close replaces them.

    Explanation

    After the try block body executes, the resources are auto-closed in the reverse of their declaration order. A try-with-resources statement is also legal with no catch and no finally clause, because providing the implicit close is its entire purpose.

  6. Question 6

    What is the output of the following program? ```java public class Main { static class Bad implements AutoCloseable { public void close() { throw new IllegalStateException("close-fail"); } } public static void main(String[] args) { try (Bad b = new Bad()) { throw new RuntimeException("body-fail"); } catch (RuntimeException e) { System.out.println(e.getMessage() + " " + e.getSuppressed()[0].getMessage()); } } } ```

    1. A. close-fail followed by an ArrayIndexOutOfBoundsException

      Treats the close failure as the primary exception; the body's exception is primary, and because the close failure was suppressed, getSuppressed()[0] exists and does not throw ArrayIndexOutOfBoundsException.

    2. B. close-fail body-fail

      Inverts the two roles by putting the close failure first as the primary exception; in fact the body's exception is primary and the close failure is the suppressed one attached to it.

    3. C. body-fail close-failCorrect answer

      The body's exception is primary, so its message prints first, and the close failure is attached via addSuppressed and retrieved from getSuppressed()[0], giving body-fail then close-fail.

    4. D. body-fail followed by an ArrayIndexOutOfBoundsException

      Correctly identifies the body exception as primary but assumes nothing was suppressed; the close failure IS suppressed, so getSuppressed()[0] returns it rather than throwing ArrayIndexOutOfBoundsException.

    Explanation

    When both the try body and a resource's close method throw, the body's exception becomes the primary exception and the close failure is attached to it as a suppressed exception, retrievable through getSuppressed(). Because a suppressed exception is present, indexing getSuppressed()[0] succeeds and yields the close failure's message rather than going out of bounds.

  7. Question 7

    What is the output of the following program? ```java public class Main { static class AppException extends Exception { AppException(Throwable cause) { super(cause); } } public static void main(String[] args) { try { try { throw new java.io.IOException("disk"); } catch (java.io.IOException e) { throw new AppException(e); } } catch (AppException e) { System.out.println(e.getCause().getMessage()); } } } ```

    1. A. null

      Expects getCause() to return null; the cause was set by passing the IOException to super(Throwable), so getCause() returns that exception rather than null.

    2. B. Compilation fails because a custom exception cannot wrap another

      Assumes custom exceptions cannot carry a cause; a subclass of Exception can pass a Throwable to super, so wrapping is a legal, standard idiom that compiles.

    3. C. diskCorrect answer

      super(Throwable) stores the IOException as the cause; getCause() recovers it and getMessage() on it returns just the message text "disk".

    4. D. java.io.IOException: disk

      This is what printing the cause object itself (its toString) would show; the code calls getMessage() on the cause, which returns only "disk" without the class-name prefix.

    Explanation

    Passing the original exception to super(Throwable) records it as the wrapped exception's cause, the standard wrap-and-rethrow idiom. Calling getCause() then recovers the IOException, and getMessage() on it returns just its message text without the class-name prefix that its toString would add.

  8. Question 8

    What is the output of the following program? ```java public class Main { static class FastFail extends RuntimeException { FastFail(String m) { super(m); } } public static void main(String[] args) { try { throw new FastFail("ff"); } catch (RuntimeException e) { System.out.println(e.getMessage()); } } } ```

    1. A. Compilation fails because main must declare throws FastFail

      A throws declaration is needed only for checked exceptions; this one is unchecked.

    2. B. ffCorrect answer

      Correct: the message given to the superclass constructor is returned by getMessage and printed.

    3. C. null

      A message was supplied, so getMessage returns it rather than null.

    4. D. FastFail

      getMessage returns the stored message text, not the class name.

    Explanation

    A subclass of RuntimeException is unchecked, so no throws clause is required anywhere. The message passed to the superclass constructor is stored and later retrieved.

Practise all 21 Handling Exceptions questions

OCP Java SE 8 has the full set, inside timed mock exams that mirror real exam conditions — every question with a worked explanation.

Open OCP Java SE 8

Other topics in this pack