Browse Certification Practice Tests by Exam Family

Java 17 1Z0-829: Handling Exceptions

Try 10 focused Java 17 1Z0-829 questions on Handling Exceptions, with explanations, then continue with IT Mastery.

On this page

Open the matching IT Mastery practice page for timed mocks, topic drills, progress tracking, explanations, and full practice.

Try Java 17 1Z0-829 on Web View full Java 17 1Z0-829 practice page

Topic snapshot

FieldDetail
Exam routeJava 17 1Z0-829
Topic areaHandling Exceptions
Blueprint weight7%
Page purposeFocused sample questions before returning to mixed practice

How to use this topic drill

Use this page to isolate Handling Exceptions for Java 17 1Z0-829. Work through the 10 questions first, then review the explanations and return to mixed practice in IT Mastery.

PassWhat to doWhat to record
First attemptAnswer without checking the explanation first.The fact, rule, calculation, or judgment point that controlled your answer.
ReviewRead the explanation even when you were correct.Why the best answer is stronger than the closest distractor.
RepairRepeat only missed or uncertain items after a short break.The pattern behind misses, not the answer letter.
TransferReturn to mixed practice once the topic feels stable.Whether the same skill holds up when the topic is no longer obvious.

Blueprint context: 7% of the practice outline. A focused topic score can overstate readiness if you recognize the pattern too quickly, so use it as repair work before timed mixed sets.

Sample questions

These questions are original IT Mastery practice items aligned to this topic area. They are designed for self-assessment and are not official exam questions.

Question 1

Topic: Handling Exceptions

The program uses only java.lang classes, so no imports are needed. What is the result of compiling and running this Java 17 code?

public class Demo {
  static String work() {
    try {
      System.out.print("A");
      throw new IllegalStateException();
    } catch (RuntimeException e) {
      System.out.print("B");
      return "C";
    } finally {
      System.out.print("D");
      throw new IllegalArgumentException();
    }
  }
  public static void main(String[] args) {
    try { System.out.print(work()); }
    catch (Exception e) { System.out.print("E"); }
  }
}

Options:

  • A. It prints ABDC.

  • B. It prints ABDE.

  • C. It prints ABCDE.

  • D. It does not compile because work() might not return a value.

Best answer: B

Explanation: The code compiles and prints ABDE. The try block throws an exception, the catch block begins a return, and the finally block executes before that return can complete. Because finally throws, the pending return value is discarded and the caller catches the new exception.

A finally block runs after the selected catch block, even when that catch block is returning a value. Here, the try block prints A and throws IllegalStateException. The catch block handles it, prints B, and prepares to return "C". Before that return reaches main, the finally block prints D and throws IllegalArgumentException. An abrupt completion from finally replaces the pending return, so System.out.print(work()) never receives "C". The exception is caught by main, which prints E.

A finally block that throws has priority over an in-progress return or earlier exception.

  • Returning C fails because the thrown exception in finally discards the catch block’s pending return.
  • Printing both C and E fails because System.out.print(work()) does not print anything if evaluating work() throws.
  • Missing return fails because a non-void method is allowed when the remaining path completes abruptly by throwing.

Question 2

Topic: Handling Exceptions

Assume this Java 17 code is compiled and run as shown:

class Door implements AutoCloseable {
    private final String id;
    Door(String id) { this.id = id; }
    public void close() { System.out.print("close " + id); }
}

public class Main {
    public static void main(String[] args) {
        Door d = new Door("A");
        try (d) {
            System.out.print("open ");
        }
        d = new Door("B");
    }
}

What is the result?

Options:

  • A. It does not compile because resources must be declared inside try.

  • B. It does not compile because d is not effectively final.

  • C. It prints open close Aclose B.

  • D. It prints open close A.

Best answer: B

Explanation: Java 17 allows an existing local variable to be used as a try-with-resources resource only if it is final or effectively final. The later reassignment to d means d is not effectively final, so compilation fails before any output occurs.

The core rule is that a reused resource variable in a try-with-resources statement must be final or effectively final. A local variable is effectively final only if it is not reassigned after its initialization. In this code, d is initialized with new Door("A"), then used in try (d), but later assigned new Door("B"). That later assignment is enough to make d not effectively final for the entire method.

Java 17 does permit resource reuse syntax such as try (d), but only when the reused variable satisfies the final/effectively-final requirement.

  • Runtime output choices fail because the code is rejected at compile time before close() can run.
  • Second door closing is not possible because the later new Door("B") assignment is never reached.
  • Resource declaration only is outdated; Java 9 and later allow reused resource variables when they are final or effectively final.

Question 3

Topic: Handling Exceptions

While compiling a small utility, a developer gets unreported exception IOException; must be caught or declared to be thrown on the throw new IOException line. The I/O failure should remain a recoverable condition.

import java.io.IOException;

public class ConfigTool {
    static String readConfig(String name) {
        if (name == null) throw new IllegalArgumentException("name");
        if (name.isBlank()) throw new IOException("missing file");
        return "ok";
    }
    public static void main(String[] args) {
        System.out.println(readConfig(""));
    }
}

What is the best cause and next fix?

Options:

  • A. Declare readConfig with throws IOException and handle the call.

  • B. Catch IllegalArgumentException inside readConfig.

  • C. Replace IOException with Error.

  • D. Catch IOException only in main.

Best answer: A

Explanation: IOException is a checked exception, unlike IllegalArgumentException, which is unchecked. Java requires checked exceptions to be caught or declared at compile time, so readConfig cannot throw IOException without a throws clause or local catch block.

Java divides Throwable types into checked exceptions, unchecked exceptions, and errors. Checked exceptions are Exception subclasses that are not RuntimeException subclasses, and the compiler enforces catch-or-declare rules for them. IOException is checked, so the compile error occurs inside readConfig where it is thrown without being caught or declared. Adding throws IOException to readConfig makes the method signature honest, and the call in main must then catch it or also declare it. IllegalArgumentException is unchecked and already needs no declaration, while Error is for serious abnormal conditions, not normal recoverable I/O problems.

  • Catching only in main fails because readConfig itself still throws a checked exception without declaring or catching it.
  • Using Error avoids the compile rule but misclassifies a recoverable I/O condition as a serious error.
  • Catching IllegalArgumentException does not address the reported IOException compile-time handling requirement.

Question 4

Topic: Handling Exceptions

A developer is checking which completion wins when a catch block returns but a finally block throws. What is printed by this Java 17 code?

public class Demo {
    static StringBuilder sb = new StringBuilder();

    static int work() {
        try {
            sb.append("T");
            throw new IllegalArgumentException();
        } catch (IllegalArgumentException e) {
            sb.append("C");
            return 1;
        } finally {
            sb.append("F");
            throw new RuntimeException("boom");
        }
    }

    public static void main(String[] args) {
        try {
            sb.append(work());
        } catch (RuntimeException e) {
            sb.append("X");
        }
        System.out.println(sb);
    }
}

Options:

  • A. It prints TC1F.

  • B. It prints TFX.

  • C. It prints TCFX.

  • D. It prints TCF1.

Best answer: C

Explanation: The catch block does execute and prepares to return 1, but the finally block still runs afterward. Because finally throws an exception, that exception overrides the pending return, so the caller catches it and appends X.

In a try/catch/finally, the finally block runs after the selected catch block, even when that catch block contains a return. If finally completes abruptly by throwing an exception, that abrupt completion replaces the pending return value. Here, try appends T and throws; catch appends C and prepares to return 1; finally appends F and throws RuntimeException; then main catches that exception and appends X. Because work() never returns a value to sb.append(work()), the 1 is not appended.

  • Return survives fails because a thrown exception from finally replaces the pending return 1.
  • Append before finally fails because work() must complete before sb.append(work()) can append the returned value.
  • Skipped catch fails because IllegalArgumentException matches the catch block before finally runs.

Question 5

Topic: Handling Exceptions

A developer is troubleshooting this Java 17 method. It fails to compile at try (reader) with: variable reader used as a try-with-resources resource neither final nor effectively final. What is the best cause?

static String readFirst(Path path) throws IOException {
    BufferedReader reader = Files.newBufferedReader(path);
    try (reader) {
        return reader.readLine();
    } finally {
        reader = null;
    }
}

Options:

  • A. BufferedReader is invalid because its close() method throws IOException.

  • B. Java 17 requires resources to be declared inside the parentheses.

  • C. The method must catch IOException instead of declaring it.

  • D. The finally assignment makes reader not effectively final.

Best answer: D

Explanation: Java 17 allows an existing local variable in a try-with-resources header only if that variable is final or effectively final. The later assignment in the finally block prevents reader from being effectively final, so the resource reuse form is rejected at compile time.

The core rule is effective-final resource reuse in try-with-resources. Since Java 9, try (reader) is legal when reader is an existing local variable that is final or effectively final and implements AutoCloseable. A variable is not effectively final if it is assigned again anywhere in its scope. Here, reader = null in the finally block is a reassignment, so reader cannot be reused as the resource. Removing that reassignment, or using a separate resource variable, would allow automatic closing to work.

Declaring throws IOException is sufficient for both readLine() and close() exceptions.

  • Resource declaration myth fails because Java 17 permits reusing an existing effectively final resource variable.
  • Close exception concern fails because try-with-resources can handle resources whose close() throws a checked exception when it is declared or caught.
  • Catch requirement fails because a method may declare throws IOException instead of catching it locally.

Question 6

Topic: Handling Exceptions

Assume all classes are in the same package; imports are not material. What is the result of compiling and running this Java 17 code?

class DataProblem extends Exception {}
class DiskProblem extends DataProblem {}

class Parser {
    void parse() throws DiskProblem { }
}

class CsvParser extends Parser {
    @Override
    void parse() throws DataProblem { }
}

public class Test {
    public static void main(String[] args) {
        Parser p = new CsvParser();
        try {
            p.parse();
            System.out.print("parsed");
        } catch (DataProblem e) {
            System.out.print("data");
        }
    }
}

Options:

  • A. It does not compile because catch (DataProblem e) is unreachable.

  • B. It compiles and prints data.

  • C. It does not compile because CsvParser.parse() throws a broader checked exception.

  • D. It compiles and prints parsed.

Best answer: C

Explanation: The code fails at compile time because of the overriding method’s throws clause. DataProblem is a superclass of DiskProblem, so CsvParser.parse() declares a broader checked exception than Parser.parse() allows.

For checked exceptions, an overriding method can declare the same exception, a subclass of that exception, or no checked exception. It cannot widen the checked exception contract of the superclass method. Here, Parser.parse() declares throws DiskProblem, but CsvParser.parse() declares throws DataProblem, which is broader because DiskProblem extends DataProblem. That makes the override invalid before main() can run.

The catch (DataProblem e) block is not the problem: a superclass catch can handle a possible DiskProblem from the declared type Parser. The key takeaway is that override compatibility is checked independently of the later try/catch.

  • Unreachable catch is tempting, but DataProblem can catch the declared DiskProblem from p.parse().
  • Normal output cannot occur because the invalid override prevents compilation.
  • Exception output cannot occur because parse() has an empty body and, more importantly, the program never compiles.

Question 7

Topic: Handling Exceptions

In Java 17, what is observed by the caller for check(true) and check(false), in that order?

static String check(boolean flag) {
    try {
        if (flag) return "try";
        throw new IllegalStateException("try");
    } finally {
        if (flag) return "finally";
        throw new IllegalArgumentException("finally");
    }
}

Options:

  • A. check(true) returns "finally"; check(false) throws IllegalArgumentException.

  • B. check(true) returns "try"; check(false) throws IllegalStateException.

  • C. check(true) returns "finally"; check(false) throws IllegalStateException.

  • D. The method does not compile because finally cannot return or throw.

Best answer: A

Explanation: A finally block runs after the try block starts to complete. If the finally block itself completes abruptly, such as with return or throw, that abrupt completion is what the caller observes.

The core rule is that finally can override a pending completion from try or catch. For check(true), the try block prepares to return "try", but the finally block then returns "finally", so that value is observed. For check(false), the try block throws IllegalStateException, but the finally block throws IllegalArgumentException, so the later exception is observed instead. Ordinary try/finally does not automatically add the first exception as suppressed; that behavior is associated with try-with-resources cleanup.

  • Earlier return wins fails because a finally return replaces the pending try return.
  • Earlier exception wins fails because the exception thrown from finally masks the earlier exception.
  • Compilation error fails because Java permits finally to complete abruptly, including by return or throw.

Question 8

Topic: Handling Exceptions

A service method must call all three helper methods. The team does not want process() to catch anything, and it wants the method declaration to include only the exception types callers are required to handle because of these calls.

class BadInputException extends Exception {}
class RetryLaterException extends RuntimeException {}

static void load() throws BadInputException { }
static void waitForSignal() throws InterruptedException { }
static void validate() throws RetryLaterException { }

static void process() {
    load();
    waitForSignal();
    validate();
}

Which exception handling choice correctly applies the Java SE 17 rule?

Options:

  • A. Declare BadInputException and InterruptedException.

  • B. Catch RetryLaterException inside process().

  • C. Declare Exception only.

  • D. Declare RetryLaterException only.

Best answer: A

Explanation: Checked exceptions must be caught or declared by the method that can throw them. BadInputException extends Exception, and InterruptedException is also checked, so process() must declare those if it does not catch them. RetryLaterException is unchecked because it extends RuntimeException.

Java separates exceptions into checked and unchecked categories. A checked exception is any Throwable that is not a RuntimeException or Error, and a method that may throw one must either catch it or declare it with throws. Here, load() can throw BadInputException, and waitForSignal() can throw InterruptedException; both are checked. validate() can throw RetryLaterException, but it is unchecked, so Java does not require process() to declare it. Declaring only the two checked exceptions satisfies the compile-time rule and avoids adding an unnecessary broad throws Exception.

  • Unchecked focus fails because declaring only RetryLaterException leaves the checked exceptions unhandled.
  • Too broad compiles, but it does not meet the requirement to declare only required exception types.
  • Wrong catch target fails because catching only RetryLaterException does not handle BadInputException or InterruptedException.

Question 9

Topic: Handling Exceptions

A developer is checking how a try-with-resources block reports failures from the main work and from cleanup. What is the result of running this code?

class Link implements AutoCloseable {
    void send() { throw new IllegalStateException("send"); }
    public void close() { throw new RuntimeException("close"); }
}

public class Test {
    public static void main(String[] args) {
        try (var link = new Link()) {
            link.send();
        } catch (Exception e) {
            System.out.print(e.getMessage() + ":" +
                    e.getSuppressed()[0].getMessage());
        }
    }
}

Options:

  • A. It prints send:close.

  • B. It prints close only.

  • C. It does not compile because close() throws unchecked exception.

  • D. It prints close:send.

Best answer: A

Explanation: In try-with-resources, an exception thrown from the try block is the primary exception. If closing the resource also throws, that cleanup exception is attached to the primary exception as suppressed. Therefore the caught exception has message send, and its first suppressed exception has message close.

The core rule is that try-with-resources preserves the original failure from the try block. Cleanup still happens, but if close() throws while another exception is already being thrown, the cleanup exception does not replace the primary exception. It is stored in the primary exception’s suppressed-exception list and can be retrieved with getSuppressed().

Here, link.send() throws IllegalStateException("send"). Then close() runs and throws RuntimeException("close"). The catch block receives the send exception and reads the first suppressed exception, which has message close.

If the try block had completed normally, the close() exception would have been the thrown exception instead.

  • Cleanup replaces primary fails because try-with-resources keeps the try-block exception as primary.
  • Cleanup only would apply only if the try block completed normally before close() failed.
  • Compilation failure is wrong because unchecked exceptions do not need to be declared or caught.

Question 10

Topic: Handling Exceptions

A developer refactors a method to use try-with-resources, but this Java 17 code does not compile. The method should create only the Upload that is actually sent and should close it automatically. Which refactor is the best fix?

class Upload implements AutoCloseable {
    void send() { System.out.print("sent "); }
    public void close() { System.out.print("closed"); }
}

static void run() {
    Upload upload = new Upload();
    upload = new Upload();
    try (upload) {
        upload.send();
    }
}

Options:

  • A. Use try (new Upload()) { upload.send(); }.

  • B. Add final to Upload upload and keep both assignments.

  • C. Use try (var upload) { upload.send(); } after the assignments.

  • D. Use try (Upload upload = new Upload()) { upload.send(); }.

Best answer: D

Explanation: The existing upload variable is reassigned, so it is not effectively final and cannot be used as an existing resource in a try-with-resources statement. Declaring the Upload directly in the try header creates a valid AutoCloseable resource and ensures it is closed automatically.

In Java 17, a try-with-resources resource must be either a local resource declaration or a reference to a final or effectively final variable. Upload is a valid resource type because it implements AutoCloseable, but the local variable upload is assigned twice before the try, so try (upload) is invalid. Moving the creation into the resource header creates a new local variable whose scope is the try block and whose close() method is called automatically after the block completes.

The key rule is that resource syntax is restricted; it is not a place for arbitrary expressions or uninitialized var declarations.

  • Resource expression fails because try (new Upload()) is not a valid resource declaration or variable reference.
  • Final reassignment fails because a final local variable cannot be assigned twice.
  • Bare var fails because var requires an initializer in a local variable declaration.

Continue with full practice

Use the Java 17 1Z0-829 Practice Test page for the full IT Mastery route, mixed-topic practice, timed mock exams, explanations, and web/mobile app access.

Try Java 17 1Z0-829 on Web View Java 17 1Z0-829 Practice Test

Free review resource

Read the Java 17 1Z0-829 Cheat Sheet on Tech Exam Lexicon, then return to IT Mastery for timed practice.

Revised on Thursday, May 14, 2026