Handling Exceptions practice questions

From OCA Java SE 8 (1Z0-808) · 19 questions on this topic

Handling Exceptions practice questions from OCA Java SE 8 (1Z0-808). This pack has 19 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 result of compiling the following program? ```java public class Main { static void load() throws java.io.IOException { } public static void main(String[] args) { load(); System.out.println("loaded"); } } ```

    1. A. loaded

      main never compiles: the checked IOException that load() declares is neither caught nor declared.

    2. B. Compilation failsCorrect answer

      The catch-or-declare rule follows the DECLARATION: load() declares IOException, so main must handle or declare it (JLS 8 §11.2).

    3. C. It compiles because load() never actually throws

      The rule follows the declaration, not the body — an empty body does not excuse callers.

    4. D. An exception is thrown at runtime

      The empty body throws nothing; the failure is the compile-time catch-or-declare rule.

    Explanation

    The catch-or-declare rule follows the DECLARATION, not the body: load() declares IOException, so every caller must handle or declare it — even though the body is empty (`It compiles because load() never actually throws` is wrong). main needs try-catch or its own throws clause.

  2. Question 2

    A class's static initializer block throws a RuntimeException when the class is first used. What does the JVM throw to the code that triggered the class's initialization?

    1. A. The original RuntimeException

      The JVM does not propagate the initializer's exception directly; it wraps it in an ExceptionInInitializerError (keeping the RuntimeException only as the cause).

    2. B. ClassNotFoundException

      ClassNotFoundException arises from reflective loading of a class by name, not from a static initializer that throws during initialization.

    3. C. NoClassDefFoundError

      NoClassDefFoundError signals a class present at compile time that is missing at runtime, not a static initializer that threw during its execution.

    4. D. ExceptionInInitializerErrorCorrect answer

      When a static initializer throws, the JVM wraps it in ExceptionInInitializerError (with the original throwable as its cause) and delivers that to the triggering code.

    Explanation

    A throwing static initializer is wrapped in ExceptionInInitializerError (with the original as its cause). `NoClassDefFoundError` is different — the class file existed at compile time but is missing at runtime; `ClassNotFoundException` comes from reflective loading by name.

  3. Question 3

    What is the output of the following program? ```java public class Main { static int pick(boolean b) { if (b) { return 1; } throw new IllegalStateException("no pick"); } public static void main(String[] args) { System.out.println(pick(true)); } } ```

    1. A. Compilation fails because not every path returns a value

      Overlooks that a throw statement satisfies the must-return rule: every path either returns a value or throws, so the method compiles (JLS 8 §8.4.7).

    2. B. It terminates with an IllegalStateException

      The throw only executes on the false branch; the call passes true, so the return path runs and the exception is never created.

    3. C. 1Correct answer

      The method compiles (a throw counts as a completing path, and the unchecked IllegalStateException needs no throws clause), and with true the return path runs, printing 1.

    4. D. Compilation fails because the throw is not declared

      Applies the declare-or-handle rule to an unchecked type. IllegalStateException is a RuntimeException, so no throws clause is required (JLS 8 §11.2).

    Explanation

    A throw statement SATISFIES the must-return rule — every path either returns or throws, so the method compiles (`Compilation fails because not every path...` is wrong). IllegalStateException is unchecked, needing no throws clause (`Compilation fails because the throw is not...` is wrong). With true, the return path runs: 1.

  4. Question 4

    What is the result of compiling the following program? ```java public class Main { static void open() throws java.io.IOException { throw new java.io.FileNotFoundException(); } public static void main(String[] args) { try { open(); } catch (java.io.IOException e) { System.out.println("io"); } catch (java.io.FileNotFoundException e) { System.out.println("fnf"); } } } ```

    1. A. io

      The program never runs because it fails to compile — the FileNotFoundException catch after the IOException catch is unreachable.

    2. B. fnf

      The FileNotFoundException catch is already covered by the preceding IOException catch, making it unreachable and the code uncompilable — so it never prints.

    3. C. Compilation failsCorrect answer

      FileNotFoundException is a subclass of IOException, which is caught first, so the second catch can never be reached — the compiler rejects it as already caught.

    4. D. io then fnf

      A single thrown exception is handled by exactly one catch, never two — and the code does not compile anyway because of the unreachable subclass catch.

    Explanation

    FileNotFoundException is a subclass of IOException, and the IOException catch comes FIRST — so the second catch can never run: "exception FileNotFoundException has already been caught". Subclass catches must precede superclass catches.

  5. Question 5

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { try { throw new OutOfMemoryError("sim"); } catch (Exception e) { System.out.println("exception"); } catch (Error e) { System.out.println("error"); } } } ```

    1. A. exception

      Error and Exception are sibling branches under Throwable, so catch (Exception) never matches an Error.

    2. B. Compilation fails because Errors cannot be thrown manually

      Throwing an Error manually is legal, just unusual.

    3. C. The program terminates with an uncaught OutOfMemoryError

      The catch (Error) clause does match OutOfMemoryError, so it is handled rather than escaping.

    4. D. errorCorrect answer

      OutOfMemoryError is an Error, and although catch (Exception) cannot match it, catch (Error) does (JLS 8 §11.1).

    Explanation

    Error and Exception are SIBLING branches under Throwable — catch (Exception) never matches an Error (so not `exception`), but catch (Error) does (so not `The program terminates with an uncaught OutOfMemoryError`). Throwing an Error manually is legal, just unusual (`Compilation fails because Errors cannot be thrown...` is wrong).

  6. Question 6

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

    1. A. first

      Assumes the exception already in flight wins. The throw inside finally replaces it, so the "first" RuntimeException is silently discarded and never reaches the outer catch.

    2. B. secondCorrect answer

      An exception thrown in finally replaces whatever was in flight (JLS 8 §14.20.2), so only the IllegalStateException carrying "second" propagates to the outer catch, which prints its message.

    3. C. firstsecond

      Only one throwable can propagate here: the finally's exception replaces the original rather than being chained or suppressed alongside it, and the catch prints a single message.

    4. D. Compilation fails

      Throwing from a finally block is legal (merely bad practice); both exceptions are unchecked, so the code compiles and runs.

    Explanation

    An exception thrown in finally REPLACES whatever was already in flight — the "first" RuntimeException is silently discarded, and only "second" propagates to the outer catch. One of the strongest reasons to keep throws (and returns) out of finally.

  7. Question 7

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try { sb.append("t"); if (sb.length() > 0) { throw new RuntimeException(); } sb.append("x"); } catch (RuntimeException e) { sb.append("c"); } finally { sb.append("f"); } System.out.println(sb); } } ```

    1. A. txcf

      The throw skips the remaining try statement entirely, so its marker is never appended.

    2. B. tf

      The RuntimeException is caught, so the catch block's marker is appended too.

    3. C. tc

      This forgets finally, which always runs and appends its marker.

    4. D. tcfCorrect answer

      t is appended, the throw skips the x append, the catch adds c, and finally always adds f: "tcf" (JLS 8 §14.20).

    Explanation

    t is appended, the throw skips the x append (`txcf` is wrong), the catch adds c, and finally always adds f (`tc` forgets it): "tcf".

  8. Question 8

    A class was present on the classpath at compile time but its .class file is missing when the program runs. What does the JVM throw when the class is first needed?

    1. A. ClassNotFoundException

      That is the CHECKED exception from reflective loading by name (Class.forName), not from a class compiled against but missing at runtime.

    2. B. ExceptionInInitializerError

      That wraps a static-initializer failure of a class that WAS found; here the class file itself is missing.

    3. C. ClassCastException

      That signals an invalid cast between types at runtime, unrelated to a missing class file.

    4. D. NoClassDefFoundErrorCorrect answer

      Compiled-against-but-missing-at-runtime is exactly NoClassDefFoundError (JavaDoc 8).

    Explanation

    Compiled-against-but-missing-at-runtime is NoClassDefFoundError. `ClassNotFoundException` is the CHECKED exception from reflective loading by name (Class.forName); `ExceptionInInitializerError` wraps a static-initializer failure of a class that WAS found.

Practise all 19 Handling Exceptions questions

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

Open OCA Java SE 8

Other topics in this pack