Handling Exceptions practice questions

From OCA Java SE 7 (1Z0-803) · 23 questions on this topic

Handling Exceptions practice questions from OCA Java SE 7 (1Z0-803). This pack has 23 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) { StringBuilder sb = new StringBuilder(); try { throw new IllegalArgumentException(); } catch (IllegalStateException | IllegalArgumentException e) { sb.append("C"); } finally { sb.append("F"); } System.out.println(sb); } } ```

    1. A. C

      This omits the finally block, which always runs and appends F after the catch appends C.

    2. B. CFCorrect answer

      The IllegalArgumentException matches the multi-catch (appends C), and finally always runs (appends F): CF.

    3. C. F

      The catch matches the thrown IllegalArgumentException and appends C before finally appends F.

    4. D. Compilation fails because two exception types share one catch

      Multi-catch legally handles either listed type in one block, so it compiles.

    Explanation

    Multi-catch (Java 7) legally handles either listed type in one block (`Compilation fails because two exception types...` is wrong). The IllegalArgumentException matches, appending C; finally always runs, appending F: "CF".

  2. Question 2

    Which category of exceptions must be either caught or declared in a throws clause when it can propagate out of a method?

    1. A. RuntimeExceptions

      RuntimeExceptions are unchecked and may propagate freely without being caught or declared.

    2. B. Errors

      Errors are unchecked and need not be caught or declared.

    3. C. Checked exceptionsCorrect answer

      The catch-or-declare rule applies only to checked exceptions.

    4. D. All Throwables

      Only checked exceptions require catch-or-declare; unchecked RuntimeExceptions and Errors do not.

    Explanation

    The catch-or-declare rule applies only to checked exceptions (Exception minus the RuntimeException branch). RuntimeExceptions and Errors are unchecked — they may propagate freely without declaration.

  3. Question 3

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { System.out.println(5 / 2 + " " + 5.0 / 0); } } ```

    1. A. 2 InfinityCorrect answer

      5 / 2 is int division giving 2, and 5.0 / 0 is floating-point division yielding Infinity.

    2. B. 2.5 Infinity

      5 / 2 is int division that truncates to 2, not 2.5.

    3. C. It throws an ArithmeticException

      Division by zero throws only for integer types; 5.0 / 0 is floating-point and yields Infinity.

    4. D. 2 NaN

      5.0 / 0 gives Infinity; NaN would come from 0.0 / 0.

    Explanation

    5 / 2 is int division → 2. Division by zero throws ArithmeticException ONLY for integer types; 5.0 / 0 is floating-point and yields Infinity (NaN would come from 0.0 / 0). So: "2 Infinity".

  4. Question 4

    What is the output of the following program? ```java public class Main { static StringBuilder log = new StringBuilder(); static void run(int n) { try { if (n == 0) { throw new RuntimeException("boom"); } log.append("T"); } catch (RuntimeException e) { log.append("C"); return; } finally { log.append("F"); } log.append("X"); } public static void main(String[] args) { run(1); run(0); System.out.println(log); } } ```

    1. A. TFCF

      This forgets that after run(1) completes without an exception, execution continues past the try statement and appends X — the first call produces TFX, not TF.

    2. B. TFXCFX

      This wrongly appends X after the catch's `return` in run(0); because the catch executes `return`, the method exits after finally and the trailing X is never reached.

    3. C. TFXCFCorrect answer

      run(1) throws nothing: try appends T, finally appends F, then code after the try appends X (TFX). run(0) throws: catch appends C, its `return` triggers finally (F), and X is skipped (CF). Concatenated the log is TFXCF.

    4. D. TXFCF

      This reverses the finally/after-try order in run(1): finally runs when control leaves the try block, before statements following the whole try, so the order is TFX, not TXF.

    Explanation

    run(1): nothing is thrown, so the try appends T, finally appends F, and execution continues past the try statement appending X — "TFX". run(0): the throw transfers control to the catch (appends C); its `return` is preceded by the mandatory finally (appends F), and because the method returns, X is never appended — "CF". Note ordering within run(1): finally runs when control leaves the try block, before statements after the whole try statement, hence TFX rather than TXF (eliminates `TXFCF`). `TFXCFX` wrongly appends X after the catch's return; `TFCF` forgets X entirely in the first call.

  5. Question 5

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try { try { throw new RuntimeException("inner"); } finally { sb.append("1"); } } catch (RuntimeException e) { sb.append("2"); } finally { sb.append("3"); } System.out.println(sb); } } ```

    1. A. 123Correct answer

      The inner finally runs first (1), the outer catch handles the exception (2), then the outer finally runs (3): 123.

    2. B. 213

      The inner finally runs before the outer catch, so 1 precedes 2, giving 123.

    3. C. 23

      This omits the inner finally's 1, which runs as the exception unwinds before the catch.

    4. D. 12

      This omits the outer finally's 3, which always runs after the catch.

    Explanation

    The inner try has no catch, so the exception propagates — but the inner finally runs FIRST (1). The outer catch then handles it (2), and the outer finally closes out (3): "123". Finally blocks run innermost-outward as the exception unwinds.

  6. Question 6

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try { try { sb.append("A"); throw new ArithmeticException(); } catch (ArithmeticException ae) { sb.append("B"); throw new IllegalStateException(); } catch (RuntimeException re) { sb.append("C"); } finally { sb.append("D"); } } catch (IllegalStateException ise) { sb.append("E"); } System.out.println(sb); } } ```

    1. A. ABCDE

      This wrongly includes C: an exception thrown inside a catch block is not offered to sibling catch clauses of the same try, so `catch (RuntimeException)` never runs.

    2. B. ABCD

      This wrongly includes C and omits E: the sibling `catch (RuntimeException)` does not catch the exception thrown from the first catch, and that IllegalStateException propagates to the outer catch, which appends E.

    3. C. ABD

      This omits E: after the inner finally appends D, the IllegalStateException thrown in the first catch propagates to the outer try's catch, which appends E.

    4. D. ABDECorrect answer

      Inner try appends A and throws; first catch appends B and throws IllegalStateException, which siblings cannot catch; the inner finally appends D; the IllegalStateException then reaches the outer catch, which appends E — giving ABDE.

    Explanation

    The inner try appends A and throws `ArithmeticException`, handled by the first catch (appends B), which then throws `IllegalStateException`. An exception thrown inside a catch block is NOT offered to sibling catch blocks of the same try — so `catch (RuntimeException)` never runs and C is not appended. The inner finally still executes (appends D) before the `IllegalStateException` propagates to the outer try, whose catch appends E. Result: ABDE.

  7. Question 7

    What is the output of the following program? ```java public class Main { public static void main(String[] args) { try { RuntimeException boom = null; throw boom; } catch (NullPointerException npe) { System.out.println("null pointer"); } catch (RuntimeException re) { System.out.println("runtime"); } } } ```

    1. A. runtime

      The `catch (RuntimeException re)` clause never runs because the NullPointerException raised by throwing null is matched first by the earlier `catch (NullPointerException npe)` — only one catch per try executes.

    2. B. Compilation fails

      Throwing a null reference of a valid Throwable type is legal at compile time; the null-ness is only a runtime concern, so the program compiles.

    3. C. null pointerCorrect answer

      Throwing a null reference makes the throw statement itself raise a NullPointerException (JLS 7 §14.18), which is matched by the first applicable clause, `catch (NullPointerException)`, printing "null pointer".

    4. D. The program completes with no output

      This assumes throwing null is a no-op, but it actively raises a NullPointerException that is caught and prints a line — the program does produce output.

    Explanation

    Throwing a null reference is legal at compile time, but at runtime the throw statement itself raises a `NullPointerException` (JLS 7 §14.18). That NPE is matched by the first applicable catch clause — `catch (NullPointerException)` — so "null pointer" is printed. The second catch is skipped because only one catch per try can run.

  8. Question 8

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

    1. A. cache not ready

      This is only the detail message; `Throwable.toString()` prepends the fully qualified class name and a colon-space, so the class name is not dropped.

    2. B. IllegalStateException

      This drops both the package qualifier and the detail message; `toString()` includes the fully qualified name plus the message, so it reads "java.lang.IllegalStateException: cache not ready".

    3. C. A full stack trace beginning with java.lang.IllegalStateException

      A stack trace is only produced by `e.printStackTrace()`; `System.out.println(e)` calls `toString()`, which yields a single line with no stack frames.

    4. D. java.lang.IllegalStateException: cache not readyCorrect answer

      `System.out.println(e)` invokes `Throwable.toString()`, which produces the fully qualified class name, a colon-space, and the detail message — exactly this string.

    Explanation

    Printing an exception with `System.out.println(e)` invokes `Throwable.toString()`, which yields the fully qualified class name, a colon-space, and the detail message — no stack frames. A stack trace is only printed by `e.printStackTrace()` (`A full stack trace beginning with java.lang...`). `cache not ready` drops the class name and `IllegalStateException` drops both the package and the message.

Practise all 23 Handling Exceptions questions

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

Open OCA Java SE 7

Other topics in this pack