banner Test 17

Test 17 - Free Java SE 25 certification Mock test - Exam Code 1Z0-831-Oracle certified Java SE 25 Professional

Resource leaks are a classic source of bugs and try-with-resources is Java's cleanest solution to that problem. This free mock test for the Oracle 1Z0-831 looks at try-with-resources along with custom exceptions, suppressed exceptions and chaining (all of which are part of the exception handling objective for the Java SE 25 Developer certification).

You start with syntax and eligibility. The resource must implement AutoCloseable and its close method can throw a checked exception which you'll then have to deal with. From Java 9 onwards an effectively final variable declared earlier can be used directly in the resource list and the questions will check that the appropriate declarations are in fact there. You'll also be checking that resources are closed automatically in reverse order of creation and that the close happens prior to any catch or finally block. That last point is one that trips up a lot of people.

Suppressed exceptions are the bit in all the text. If both the try block and the close method throw, the try block's exception is the one that gets thrown and the close exception is suppressed. You'll know which exception the caller sees, you'll know how to get the suppressed ones via getSuppressed and you can then compare that with the case of a plain finally block where the later exception would just overwrite the earlier one.

Custom exceptions come next. You'll be deciding whether a new class should extend Exception or RuntimeException, adding constructors to take a message and a cause and carrying around any additional fields you might need for diagnostic data. There's a question on what happens if you throw a checked custom exception without a throws clause, and another one on what happens if an overriding method is found to throw it.

Exception chaining gets its own set of rules. You use the cause parameter, you call initCause and you then walk the chain using getCause to see what the stack trace will print. Related topics include the throw statement as opposed to the throws clause, rethrowing an exception that you've caught and why you can rethrow precisely and still have a very narrow method signature. You need to be very mindful of the order in which the catch and finally blocks interact with closing as that sequence is a very common source of output questions.

Each explanation goes through the sequence of events step by step. Take the test, go through the ones you got wrong and then write a small AutoCloseable class that just prints out from its constructor and its close method. Seeing the sequence in your own console is by far the quickest way to remember it.

Welcome to your Free Java SE 25 – Test 17