CCNA Java Exceptions Questions

49 questions · Java Exceptions topic · All types, answers revealed

1
MCQhard

A method catches multiple exceptions using a multi-catch clause. Which statement about the exceptions in a multi-catch clause is correct?

A.The exceptions must be disjoint; if one is a subclass of another, the code will not compile.
B.All exceptions in a multi-catch must be unchecked exceptions.
C.The multi-catch clause can have up to three exception types.
D.The exceptions can be in any order, and the first matching catch handles the exception.
AnswerA

Subclass relationship makes one unreachable, causing compile error.

Why this answer

Option A is correct because Java requires that exception types in a multi-catch clause be disjoint (i.e., not in a subclass/superclass relationship). If one exception is a subclass of another, the code will not compile because the catch block would be unreachable for the subclass exception, violating the rule that catch blocks must be ordered from most specific to most general. This ensures that the multi-catch clause is unambiguous and that each exception type is distinct.

Exam trap

The trap here is that candidates often confuse multi-catch with single-catch ordering rules, assuming that the order of exceptions in a multi-catch clause matters for handling, when in fact the compiler enforces disjointness and order is irrelevant within a single multi-catch block.

How to eliminate wrong answers

Option B is wrong because multi-catch clauses can include both checked and unchecked exceptions, as long as they are disjoint; there is no restriction that they must be unchecked. Option C is wrong because the Java Language Specification does not limit the number of exception types in a multi-catch clause to three; you can list any number of exception types separated by '|', as long as they are disjoint. Option D is wrong because the order of exceptions in a multi-catch clause does not matter for handling; the compiler checks that the types are disjoint, and if they are not, it fails compilation—there is no 'first matching catch' behavior within a single multi-catch block.

2
MCQeasy

Which of the following is a checked exception in Java?

A.NullPointerException
B.ArrayIndexOutOfBoundsException
C.SQLException
D.IllegalArgumentException
AnswerC

Checked exception.

Why this answer

SQLException is a checked exception because it extends Exception directly (not RuntimeException). Checked exceptions must be either caught with a try-catch block or declared in the method signature using 'throws'. SQLException is thrown by JDBC API methods when database access errors occur, forcing the developer to handle potential SQL failures at compile time.

Exam trap

The trap here is that candidates often confuse all exception subclasses of Exception as checked, forgetting that RuntimeException and its subclasses are unchecked, and thus incorrectly select unchecked exceptions like NullPointerException or IllegalArgumentException.

How to eliminate wrong answers

Option A is wrong because NullPointerException extends RuntimeException and is an unchecked exception; it can occur at runtime without mandatory handling. Option B is wrong because ArrayIndexOutOfBoundsException extends RuntimeException and is unchecked; it is thrown by the JVM when accessing an invalid array index and does not require explicit handling. Option D is wrong because IllegalArgumentException extends RuntimeException and is unchecked; it is used to indicate that a method has received an illegal argument and does not require compile-time handling.

3
MCQhard

Given the following assertion: assert age >= 0 : "Age must be non-negative"; When is it appropriate to use assertions?

A.To verify internal invariants of a private method.
B.To handle recoverable conditions like file not found.
C.To check parameters of a public API method.
D.To validate user input from an external system.
AnswerA

Assertions are perfect for internal consistency checks.

Why this answer

Option C is correct. Assertions are typically used for internal invariants during development and testing, not for argument validation in public methods. Options A, B, D are incorrect because assertions should not be used for input validation (checked exceptions) or for conditions that are checked externally.

4
MCQhard

Consider try-with-resources where resource1 is opened first, then resource2. During closing, both throw exceptions. Which exception is propagated to the caller?

A.The exception from resource1 (closed last) with resource2's exception as suppressed.
B.The exception from resource2 (closed first) with resource1's exception as suppressed.
C.Only the exception from the resource declared first is propagated.
D.Both exceptions are wrapped in a new exception.
AnswerB

Resources closed in reverse order; first exception encountered becomes primary.

Why this answer

In try-with-resources, resources are closed in the reverse order of their declaration. Resource2 (declared second) is closed first, and resource1 (declared first) is closed last. If both throw exceptions during closing, the exception from the first resource closed (resource2) is propagated to the caller, and the exception from the second resource closed (resource1) is added as a suppressed exception.

This matches option B.

Exam trap

The trap here is that candidates often mistakenly think the exception from the first declared resource is propagated, when in fact the exception from the resource closed first (the last declared) is propagated, and the other is suppressed.

How to eliminate wrong answers

Option A is wrong because it incorrectly states that the exception from resource1 (closed last) is propagated; in reality, the exception from the resource closed first (resource2) is propagated. Option C is wrong because it claims only the exception from the resource declared first is propagated, but the exception from the resource closed first (the last declared) is propagated, and the other exception is suppressed. Option D is wrong because both exceptions are not wrapped into a new exception; instead, one exception is propagated and the other is added as a suppressed exception via the Throwable.addSuppressed() mechanism.

5
MCQeasy

Which of the following is a best practice when designing custom exception classes?

A.Define a custom exception with a single constructor that takes an int error code.
B.Extend an existing exception class and provide constructors that call the superclass constructor.
C.Extend the Throwable class directly to create a new exception type.
D.Use a generic Exception class with a string message to indicate the type of error.
AnswerB

This matches common patterns and allows proper exception handling.

Why this answer

Option B is correct because the Java best practice for custom exceptions is to extend an existing exception class (e.g., Exception or RuntimeException) and provide constructors that call the superclass constructor. This ensures the custom exception inherits the standard exception mechanism, including proper chaining, stack trace handling, and compatibility with try-catch blocks, without reinventing the wheel.

Exam trap

Oracle often tests the misconception that extending Throwable directly is acceptable for custom exceptions, but the trap is that Throwable should only be subclassed by Error and Exception, and custom exceptions must extend Exception or RuntimeException to work correctly with Java's checked/unchecked exception rules and the compiler's exception specification enforcement.

How to eliminate wrong answers

Option A is wrong because defining a custom exception with a single constructor that takes an int error code is not a best practice; it limits flexibility and breaks the standard exception API, which expects message and cause constructors. Option C is wrong because extending Throwable directly is not recommended; Throwable is the root class, and direct subclasses are reserved for serious system errors (e.g., Error), not application-level exceptions, and it bypasses the checked/unchecked exception distinction. Option D is wrong because using a generic Exception class with a string message to indicate the type of error defeats the purpose of custom exceptions, which should provide distinct types for specific error conditions to enable precise catch-and-handle logic.

6
MCQhard

A financial trading application uses Java 17 and processes millions of transactions per second. It uses a custom checked exception `TradeException extends Exception` for business rule violations. Recently, the transaction processing service began throwing a `RuntimeException` that wraps a `TradeException`, but the error logs only show the wrapper's message and stack trace, missing the original `TradeException` details. The logging framework prints the exception and its cause chain. The development team needs to ensure that the original `TradeException` message and stack trace are always logged. What is the most appropriate course of action?

A.Catch the RuntimeException in the main processing loop and print the cause's message using getCause().getMessage().
B.Modify the exception wrapping code to pass the original TradeException as a cause to the RuntimeException constructor.
C.Modify the TradeException class to extend RuntimeException.
D.Override the getMessage() method in TradeException to return the original message.
AnswerB

Using the cause constructor preserves the original exception in the cause chain.

Why this answer

Option C is correct because the issue is that the wrapping code does not pass the original exception as a cause. By using the `RuntimeException(Throwable cause)` constructor or `RuntimeException(String message, Throwable cause)`, the original exception is preserved in the cause chain, and the logging framework will include it. Option A is a workaround but not a proper fix and could be error-prone.

Option B changes the exception type but does not address the missing cause, and may break checked exception contracts. Option D is irrelevant because the wrapper's `getMessage()` is the one being logged, not the original.

7
Multi-Selecteasy

Which THREE statements about exception handling are true? (Choose three.)

Select 3 answers
A.The variable in a catch clause is effectively final only when using multi-catch syntax.
B.A finally block is mandatory in a try-with-resources statement.
C.Multi-catch syntax uses the pipe symbol (|) between exception types.
D.Checked exceptions must be handled or declared in the throws clause.
E.A finally block will not execute if the JVM exits before the finally block.
AnswersC, D, E

Correct syntax.

Why this answer

Option C is correct because Java's multi-catch syntax allows a single catch block to handle multiple exception types by separating them with the pipe symbol (|). This reduces code duplication when different exceptions require the same handling logic.

Exam trap

The trap here is that candidates often confuse the 'effectively final' concept with multi-catch syntax, incorrectly thinking that only multi-catch variables are effectively final, when in fact all catch clause variables are implicitly final in Java.

8
MCQhard

Given an exception chain where a custom exception is created with a cause, which method is used to set the cause after construction?

A.The cause can only be set via constructor.
B.setCause(Throwable)
C.addSuppressed(Throwable)
D.initCause(Throwable)
AnswerD

Allows setting the cause after construction.

Why this answer

Option D is correct because `initCause(Throwable)` is the method provided by the `Throwable` class to set the cause of an exception after the exception has been constructed. This is useful when the exception must be created without a cause (e.g., via a no-arg constructor) and the cause is determined later. The cause can only be set once; a second call will throw an `IllegalStateException`.

Exam trap

The trap here is that candidates confuse `initCause(Throwable)` with `addSuppressed(Throwable)`, or assume the cause can only be set via constructor, missing the post-construction capability that `initCause` provides.

How to eliminate wrong answers

Option A is wrong because the cause can be set both via a constructor (e.g., `Throwable(String message, Throwable cause)`) and after construction using `initCause(Throwable)`. Option B is wrong because there is no method named `setCause(Throwable)` in the `Throwable` class or any standard Java exception class; the correct method is `initCause(Throwable)`. Option C is wrong because `addSuppressed(Throwable)` is used to add suppressed exceptions (typically in try-with-resources) and does not set the causal chain; it adds exceptions that were suppressed, not the root cause.

9
MCQhard

Given the stack trace, which statement is true about the exception handling?

A.Both exceptions are checked, and the code must handle both.
B.The RuntimeException is caused by a checked exception, so it must be declared in the throws clause.
C.The SQLException is a checked exception, and the code must handle it or declare it.
D.The RuntimeException is an unchecked exception, so it cannot be caught.
AnswerC

SQLException is checked and must be handled or declared.

Why this answer

Option C is correct because SQLException is a checked exception (a subclass of Exception but not RuntimeException), so the Java compiler enforces that it must be either caught in a try-catch block or declared in the throws clause of the enclosing method. The stack trace indicates that an SQLException occurred, and the code must handle this checked exception to compile successfully.

Exam trap

The trap here is that candidates often confuse the 'must handle or declare' rule for checked exceptions with the idea that unchecked exceptions cannot be caught at all, leading them to incorrectly select Option D.

How to eliminate wrong answers

Option A is wrong because not both exceptions are checked; RuntimeException is an unchecked exception, so the code does not have to handle it. Option B is wrong because a RuntimeException caused by a checked exception does not require the RuntimeException to be declared in the throws clause; only the checked exception itself must be handled or declared. Option D is wrong because RuntimeException, though unchecked, can still be caught; the statement that it 'cannot be caught' is false.

10
MCQeasy

In a try-finally block, what happens to a return statement inside the finally block?

A.The return in the finally block is executed, and the try block return is ignored.
B.The finally block is skipped if there is a return in try.
C.The return in the try block takes precedence.
D.If the try block throws an exception, the finally return overrides the exception.
AnswerA, D

Finally return overrides try return.

Why this answer

In a try-finally block, the finally block is always executed, even if the try block contains a return statement. If the finally block itself contains a return statement, that return value replaces any return value from the try block, effectively overriding it. This is because the finally block's return causes the method to exit immediately, discarding the try block's return value.

Exam trap

The trap here is that candidates often assume the finally block only runs for cleanup and cannot affect the return value, but the Java Language Specification explicitly allows a return in finally to override any prior return or even suppress an uncaught exception.

How to eliminate wrong answers

Option B is wrong because the finally block is never skipped when a return is in the try block; the Java Language Specification guarantees that the finally block executes after the try block completes, regardless of control flow statements like return. Option C is wrong because the return in the try block does not take precedence; the finally block's return executes after the try block's return is evaluated but before the method actually returns, so the finally return value is what the caller receives.

11
MCQeasy

A team is designing a logging framework. The framework's core method log(String message) may throw a checked LogException if the logging system fails. The team wants to allow callers to choose whether to handle the exception or declare it as thrown. Which declaration of the log method satisfies this requirement?

A.public void log(String message) throws LogException { ... }
B.public void log(String message) { ... }
C.public void log(String message) throws Error { ... }
D.public void log(String message) throws RuntimeException { ... }
AnswerA

Checked exception forces caller to handle or declare.

Why this answer

Option A is correct because it declares the checked exception LogException in the throws clause, which forces callers to either handle it with a try-catch or propagate it by declaring throws in their own method. This satisfies the requirement that callers can choose how to deal with the exception, as checked exceptions must be acknowledged at compile time.

Exam trap

Oracle often tests the distinction between checked and unchecked exceptions, and the trap here is that candidates may think omitting throws or using RuntimeException/Error allows callers to choose, but only a checked exception declared with throws enforces the handling-or-declaring choice at compile time.

How to eliminate wrong answers

Option B is wrong because omitting the throws clause means the method cannot throw a checked LogException; if the implementation attempts to throw it, the code will not compile. Option C is wrong because Error is an unchecked throwable (a subclass of Throwable but not Exception), and declaring throws Error does not enforce handling of a checked exception; it also misrepresents the exception type. Option D is wrong because RuntimeException is unchecked, so callers are not required to handle or declare it, which contradicts the requirement that LogException is a checked exception that must be explicitly handled or declared.

12
MCQhard

Given the exhibit showing output from a program that uses try-with-resources, which of the following best describes the program?

A.The try block threw an exception, but the resource closed successfully.
B.Only the close method threw an exception, and the try block did not throw.
C.Both the try block and the close method threw exceptions.
D.The close method threw an exception, and the try block completed normally.
AnswerC

Both exceptions present; close exception is suppressed.

Why this answer

Option C is correct because the output shows both a primary exception from the try block and a suppressed exception from the close method. In try-with-resources, if both the try block and the close method throw exceptions, the primary exception from the try block is propagated, and the close method's exception is added as a suppressed exception. The output displays both exceptions, confirming that both occurred.

Exam trap

Oracle often tests the misconception that only one exception can be thrown, leading candidates to think that if a close method throws, the try block's exception is lost, but in reality both are captured via suppressed exceptions.

How to eliminate wrong answers

Option A is wrong because it states only the try block threw an exception and the resource closed successfully, but the output shows an exception from the close method as well. Option B is wrong because it claims only the close method threw an exception and the try block did not throw, yet the output includes a primary exception from the try block. Option D is wrong because it says the close method threw an exception and the try block completed normally, but the output clearly shows a primary exception from the try block, not normal completion.

13
MCQmedium

What is the output when the code is executed?

A.Arithmetic Finally
B.Arithmetic Exception Finally
C.Exception Finally
D.Arithmetic Finally [stack trace]
AnswerD

Correct: 'Arithmetic' is printed, then finally prints 'Finally', then the rethrown exception causes a stack trace.

Why this answer

Option D is correct because the code throws an ArithmeticException (division by zero) inside the try block, which is caught by the first catch block (ArithmeticException). The finally block always executes after the catch block, printing 'Finally'. The stack trace is printed because the exception is re-thrown in the catch block (implicitly or explicitly) and not handled, causing the program to terminate with an uncaught exception.

The output shows 'Arithmetic', then 'Finally', followed by the stack trace.

Exam trap

The trap here is that candidates forget that a re-thrown exception produces a stack trace, or they mistakenly think the generic Exception catch block will execute after the specific one, leading them to choose Option B or C.

How to eliminate wrong answers

Option A is wrong because it omits the stack trace; the re-thrown exception must produce a stack trace. Option B is wrong because it includes 'Exception' as a separate output; the ArithmeticException is caught first, and the generic Exception catch block is never reached. Option C is wrong because it shows 'Exception' instead of 'Arithmetic'; the specific ArithmeticException catch block matches first, so 'Arithmetic' is printed, not 'Exception'.

14
MCQhard

Given a method that throws IOException, SQLException, and TimeoutException, a developer writes a catch block that rethrows the exception. Using Java 17, which exception types can the catch block declare in its throws clause if the rethrown exception is not modified?

A.The method must declare all checked exceptions individually.
B.Only the common superclass of the exceptions (Exception).
C.No throws clause is needed if the catch block logs and returns.
D.Any single exception type that covers all caught exceptions.
AnswerA

Yes, you can list IOException, SQLException, TimeoutException in throws.

Why this answer

With improved type inference, if the exception parameter is effectively final and not modified, the compiler infers the precise exception types. Option D is correct: the throws clause can list all three checked exceptions individually. Option A is too narrow.

Option B is possible but not best. Option C is incorrect because Exception is too broad.

15
MCQhard

Given a try-with-resources statement where both the try block and the close method of the resource throw exceptions, which of the following is true about exception handling?

A.The exception from the close method is the primary exception.
B.Both exceptions are thrown simultaneously, causing a multi-catch.
C.The try block exception is the primary exception; the close exception is suppressed.
D.The close method exception is ignored if the try block succeeds.
AnswerC

Correct behavior of try-with-resources.

Why this answer

In a try-with-resources statement, if both the try block and the resource's close() method throw exceptions, the exception from the try block is the primary exception, and any exception thrown by close() is added as a suppressed exception. This is defined by Java's try-with-resources semantics (JLS §14.20.3.2), ensuring the primary exception is not masked by resource cleanup failures.

Exam trap

The trap here is that candidates often think both exceptions are thrown simultaneously or that the close exception is ignored, but Java's suppressed exception mechanism ensures the try block exception remains primary while preserving the close exception for debugging.

How to eliminate wrong answers

Option A is wrong because the exception from the close method is never the primary exception; the try block exception takes precedence, and the close exception is suppressed. Option B is wrong because Java does not throw both exceptions simultaneously; instead, the close exception is suppressed and attached to the primary exception via Throwable.addSuppressed(). Option D is wrong because if the try block succeeds, any exception thrown by close() is not ignored; it is thrown as the primary exception from the entire try-with-resources statement.

16
MCQmedium

Given the following code snippet inside a method: try { // risky code } catch (IOException | SQLException e) { // handle } What is the implicit type of the exception variable 'e' in the catch block?

A.It is of type Object.
B.It is of type Exception.
C.It is of type Throwable.
D.It is either IOException or SQLException.
AnswerB

The common base of IOException and SQLException is Exception.

Why this answer

In Java, when a multi-catch clause catches multiple exception types (e.g., IOException | SQLException), the compiler infers the catch parameter's type as the closest common superclass that is not Object or Throwable. Since IOException and SQLException both extend Exception directly, the implicit type of 'e' is Exception. This allows the catch block to handle both exception types polymorphically.

Exam trap

The trap here is that candidates mistakenly think 'e' has a union type (like TypeScript) or that the compiler uses the first listed exception type, when in fact Java infers the most specific common superclass, which is Exception for IOException and SQLException.

How to eliminate wrong answers

Option A is wrong because the implicit type is not Object; the compiler selects the most specific common superclass, which is Exception, not Object. Option C is wrong because Throwable is too broad; the common superclass of IOException and SQLException is Exception, not Throwable. Option D is wrong because 'e' is not a union type; it is a single type (Exception) that can reference either IOException or SQLException at runtime, but its compile-time type is Exception.

17
Multi-Selecthard

Which THREE practices are recommended for effective exception handling? (Choose three.)

Select 3 answers
A.Throw exceptions early, catch them late, but handle them at the appropriate level.
B.Define custom exceptions without providing any additional context.
C.Use try-with-resources for automatic resource management instead of manual close in finally.
D.Catch exceptions at the highest level of the application and log them generically.
E.Use specific exception types in catch blocks rather than catching Exception.
AnswersA, C, E

Best practice: throw at point of error, catch where recovery is possible.

Why this answer

Option A is correct because effective exception handling in Java recommends throwing exceptions as soon as an error is detected (fail-fast), catching them at a level where the error can be meaningfully handled (not too early), and handling them at the appropriate layer of abstraction. This prevents swallowing exceptions or losing context, and aligns with the principle of separation of concerns.

Exam trap

Oracle often tests the misconception that catching exceptions at the highest level with generic logging is a good practice, when in fact it hides errors and violates the principle of handling exceptions at the appropriate level.

18
Multi-Selecthard

Which TWO statements about creating custom exceptions are correct? (Choose two.)

Select 2 answers
A.Custom exceptions should extend Error to indicate fatal errors.
B.Custom exception classes should be declared final to prevent subclassing.
C.Custom exceptions must implement the Exception interface.
D.It is good practice to provide a constructor that takes a String message and a Throwable cause.
E.When calling super(cause) in a custom exception constructor, the cause is automatically set.
AnswersD, E

Common to have such constructor.

Why this answer

Option D is correct because it is a well-established best practice in Java to provide a constructor that accepts both a String message and a Throwable cause, enabling precise error reporting and chaining of exceptions. This allows developers to pass a human-readable description along with the underlying cause, which is essential for debugging and logging.

Exam trap

The trap here is that candidates often confuse the requirement to extend Throwable (or a subclass) with implementing a nonexistent Exception interface, or they mistakenly think that custom exceptions must be declared final to prevent misuse, when in fact Java allows and encourages subclassing of custom exceptions for more granular error handling.

19
Multi-Selectmedium

Which TWO of the following are checked exceptions in Java?

Select 2 answers
A.SQLException
B.ArithmeticException
C.ArrayIndexOutOfBoundsException
D.NullPointerException
E.IOException
AnswersA, E

SQLException is a checked exception.

Why this answer

A is correct because `SQLException` is a subclass of `java.lang.Exception` (which is a checked exception class) and does not extend `RuntimeException`. Checked exceptions must be either caught or declared in the method signature; `SQLException` is commonly thrown when database access errors occur, such as connection failures or SQL syntax errors.

Exam trap

The trap here is that candidates often confuse runtime exceptions (unchecked) with checked exceptions, mistakenly thinking that any exception that can occur at runtime is checked, but the key distinction is whether the exception class extends `RuntimeException` or not.

20
Multi-Selectmedium

Which TWO statements about try-with-resources are true? (Choose two.)

Select 2 answers
A.Resources are closed in the order they are declared.
B.If both the try block and the close method throw exceptions, the close exception is suppressed.
C.Only a single resource can be managed in a try-with-resources statement.
D.Resources must implement AutoCloseable.
E.Resources are closed after the catch block if an exception occurs.
AnswersB, D

Suppressed exception mechanism.

Why this answer

Option B is correct because when both the try block and the close method throw exceptions, the exception from the close method is suppressed and added to the suppressed exceptions list of the exception thrown by the try block. This behavior is defined by the try-with-resources specification in Java, ensuring that the primary exception is not masked by resource-closing exceptions.

Exam trap

The trap here is that candidates often assume resources close in declaration order (A) or that only one resource is allowed (C), but the exam tests the reverse close order and the ability to manage multiple resources, as well as the precise timing of resource closure relative to catch blocks.

21
MCQhard

Your team manages a high-throughput financial transaction system running on Java 17. Recently, the application experiences intermittent slowdowns and increased CPU usage during peak hours. Monitoring reveals that exception handling code is invoked frequently due to validation errors in incoming data. The system uses a central exception handler that logs every exception and throws a custom ApplicationException. In many places, the code catches generic Exception and rethrows the custom exception after logging. Additionally, method signatures include throws Exception. The team wants to improve performance and maintainability without changing the external behavior significantly. Which course of action best addresses the performance and maintainability issues?

A.Change all catch blocks to catch Throwable and ignore irrecoverable errors to reduce logging.
B.Add a try-catch block around every method call that might throw an exception to handle locally.
C.Define specific custom checked exception classes for each validation error and catch them precisely, avoiding generic Exception catches.
D.Wrap all exceptions in a single custom unchecked exception to simplify exception handling.
AnswerC

Precise catch reduces unnecessary handling and improves performance.

Why this answer

Option C is correct because catching generic `Exception` forces the JVM to build a full stack trace for every validation error, which is expensive in a high-throughput system. By defining specific custom checked exception classes and catching them precisely, the team reduces unnecessary stack trace generation and makes the code more maintainable by clearly documenting which errors are expected. This approach aligns with Java best practices for exception handling, improving both performance and code clarity without altering external behavior.

Exam trap

The trap here is that candidates often think wrapping all exceptions in a single unchecked exception simplifies code (Option D), but the exam tests the principle that precise exception handling improves both performance and maintainability, while broad catches or unchecked wrappers degrade them.

How to eliminate wrong answers

Option A is wrong because catching `Throwable` includes `Error` subclasses (e.g., `OutOfMemoryError`), which are irrecoverable and should not be caught or ignored; doing so can mask critical JVM failures and violate Java's exception hierarchy design. Option B is wrong because adding a try-catch around every method call that might throw an exception leads to excessive nesting, code duplication, and still does not address the root cause of generic `Exception` catches; it also degrades performance by adding unnecessary control flow overhead. Option D is wrong because wrapping all exceptions in a single custom unchecked exception (e.g., extending `RuntimeException`) eliminates compile-time checking, making it harder to handle specific validation errors and potentially hiding bugs; it also forces callers to either catch a broad type or let exceptions propagate unchecked, which is the opposite of maintainability.

22
Multi-Selecthard

Which TWO statements about the try-with-resources statement are correct? (Choose two.)

Select 2 answers
A.The resource class must implement AutoCloseable.
B.The resource variable must be declared as final.
C.Resources are closed in the reverse order of their declaration.
D.A try-with-resources statement cannot have a finally block.
E.Resources are closed before the try block executes.
AnswersA, C

Correct: only AutoCloseable resources are allowed.

Why this answer

Option A is correct because the try-with-resources statement requires that each resource implements the AutoCloseable interface (or its subinterface Closeable). This interface defines the close() method, which is automatically invoked by the JVM when the try block completes, ensuring proper resource management without explicit finally blocks.

Exam trap

The trap here is that candidates often think resources must be declared with the final keyword (Option B) or that finally blocks are prohibited (Option D), but the exam tests the exact JLS rules: resources are effectively final, and finally blocks are allowed but execute after resource closure.

23
MCQeasy

What happens when a finally block throws an exception?

A.The JVM logs both exceptions and then terminates the thread.
B.The exception from the try block is propagated and the finally exception is ignored.
C.Both exceptions are reported as suppressed exceptions of a new exception.
D.The exception from the try block is suppressed and the finally exception is reported.
AnswerD

The exception from finally takes precedence, the try exception is lost unless caught as suppressed.

Why this answer

Option D is correct because when a finally block throws an exception, the JVM suppresses the exception that was thrown from the try block (if any) and propagates the exception thrown from the finally block. This behavior is defined in the Java Language Specification (JLS §14.20.2) and ensures that the finally block's exception takes precedence, as the finally block is executed after the try block completes abruptly.

Exam trap

The trap here is that candidates often assume both exceptions are lost or that the try-block exception always propagates, but the Java Language Specification mandates that the finally-block exception takes precedence, with the try-block exception being suppressed.

How to eliminate wrong answers

Option A is wrong because the JVM does not log both exceptions and terminate the thread; instead, it suppresses the try-block exception and propagates the finally-block exception. Option B is wrong because the exception from the try block is not propagated; it is suppressed, and the finally exception is reported instead. Option C is wrong because both exceptions are not reported as suppressed exceptions of a new exception; only the try-block exception is suppressed, and the finally-block exception is the one thrown, with the try-block exception added as a suppressed exception to the finally-block exception (if the finally-block exception is a subtype of Throwable that supports suppression).

24
MCQmedium

Given the exhibit showing a compilation error at line 5 of Test.java, which of the following code fragments could be at that line?

A.FileInputStream fis = new FileInputStream("test.txt");
B.int x = 5;
C.try { ... } catch (Exception e) { }
D.System.out.println("Hello");
AnswerA

FileInputStream constructor throws FileNotFoundException (subclass of IOException).

Why this answer

Option A is correct because the code at line 5 is a checked exception (FileNotFoundException) that must be handled or declared. The compilation error indicates that the method containing line 5 does not handle or declare this checked exception, which is required by the Java compiler.

Exam trap

The trap here is that candidates often forget that checked exceptions must be handled or declared, and mistakenly think any code that throws an exception will compile as long as it is inside a method, ignoring the compiler's requirement for checked exception handling.

How to eliminate wrong answers

Option B is wrong because assigning an int literal to a variable does not throw any checked exception and would not cause a compilation error at line 5. Option C is wrong because a try-catch block is syntactically valid and would not cause a compilation error on its own; the error is likely due to an unhandled checked exception inside the try block, not the catch clause itself. Option D is wrong because printing a string literal does not throw any checked exception and would compile without error.

25
Multi-Selecteasy

Which TWO of the following are unchecked exceptions? (Choose two.)

Select 2 answers
A.SQLException
B.Exception
C.NullPointerException
D.ArrayIndexOutOfBoundsException
E.IOException
AnswersC, D

Unchecked runtime exception.

Why this answer

NullPointerException (option C) is an unchecked exception because it extends RuntimeException, which means it is not checked at compile time. The Java compiler does not require you to handle or declare NullPointerException, making it an unchecked exception.

Exam trap

The trap here is that candidates often confuse 'Exception' (the superclass) as unchecked, but Exception itself is a checked exception; only RuntimeException and its subclasses are unchecked.

26
MCQeasy

You are developing a microservice that processes financial transactions. The service reads transaction data from a message queue, validates it, and writes results to a database. The code uses a try-with-resources statement to manage database connections. During testing, you notice that when a transaction fails validation, the service throws an IllegalStateException before closing the database connection, causing a resource leak. You need to ensure that the database connection is always closed properly, even if an exception is thrown during validation. The current code structure is: try (Connection conn = DriverManager.getConnection(url, user, pass)) { // read from queue // validate transaction // if invalid, throw new IllegalStateException("Invalid transaction"); // write to database } Which course of action would you recommend?

A.Move the connection creation outside the try-with-resources to manually manage it.
B.No change is needed; the try-with-resources ensures the connection is closed.
C.Replace the try-with-resources with a try-catch-finally block and close the connection in the finally block.
D.Add a catch block to catch the IllegalStateException and close the connection.
AnswerB

try-with-resources automatically closes the resource, even if an exception is thrown.

Why this answer

Option B is correct because try-with-resources automatically closes any resource that implements AutoCloseable (including Connection) when the try block exits, whether normally or via an exception. The IllegalStateException thrown during validation does not prevent the connection from being closed; the close() method is called as part of the implicit finally block generated by the compiler.

Exam trap

The trap here is that candidates mistakenly think an uncaught exception bypasses resource cleanup, but try-with-resources guarantees closure regardless of how the block exits, including exceptions.

How to eliminate wrong answers

Option A is wrong because moving the connection outside try-with-resources would require manual management and increase the risk of resource leaks if an exception occurs before the manual close. Option C is wrong because replacing try-with-resources with a try-catch-finally block is unnecessary and less concise; try-with-resources already guarantees closure without explicit finally code. Option D is wrong because adding a catch block to close the connection is redundant and could lead to double-close issues; try-with-resources handles closure automatically even without a catch.

27
MCQeasy

You are developing a batch processing application that reads records from a CSV file and parses each row into an integer ID. The reading method readNextRecord() returns a String and can throw IOException and NumberFormatException. The method processID(int id) processes the ID. The entire process runs in a for loop over 10,000 records. The requirement is that if any record fails (either due to file read error or parsing), the loop must continue to the next record, but the exception must be logged for later review. Which approach best achieves this requirement?

A.Surround the entire loop with a try-catch block that catches IOException and NumberFormatException using multi-catch, logs once, and allows the loop to continue.
B.Inside the loop, wrap the calls in a try-catch that catches Exception, logs, and continues.
C.Declare the method to throw IOException and NumberFormatException and let the caller handle them.
D.Inside the loop, wrap the readNextRecord() and processID() calls in a try-catch block that catches IOException and NumberFormatException separately, logs the exception, and continues.
AnswerD

Correct: isolates each iteration and catches specific exceptions.

Why this answer

Option D is correct because it places a try-catch block inside the loop that catches IOException and NumberFormatException separately, logs each exception, and then continues to the next iteration. This ensures that a failure in reading or parsing any single record does not terminate the loop, and each exception is logged individually for later review, meeting the requirement precisely.

Exam trap

The trap here is that candidates often think catching a broad Exception or wrapping the entire loop in a try-catch is sufficient, but they overlook the requirement that the loop must continue after each failure, which demands the try-catch be inside the loop, not outside.

How to eliminate wrong answers

Option A is wrong because surrounding the entire loop with a try-catch block would cause the loop to terminate as soon as the first exception occurs; the catch block would log once and exit the loop, not continue to the next record. Option B is wrong because catching the overly broad Exception class is poor practice; it could mask unexpected runtime exceptions (e.g., NullPointerException) that should not be silently swallowed, violating the principle of catching only specific checked exceptions. Option C is wrong because declaring the method to throw IOException and NumberFormatException would propagate exceptions to the caller, aborting the loop entirely rather than continuing to the next record.

28
Drag & Dropmedium

Order the steps to compile and run a simple Java program from the command line.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

javac produces .class files; java runs the main method of the specified class. The classpath may need to be set if dependencies exist.

29
MCQeasy

A method reads a file and throws IOException. Which of the following is the correct way to declare the method?

A.public void readFile() throws RuntimeException { ... }
B.public void readFile() throws Exception { ... }
C.public void readFile() { ... } // assumes try-catch inside
D.public void readFile() throws IOException { ... }
AnswerD

Correctly declares IOException.

Why this answer

Option D is correct because the method explicitly declares that it throws IOException, which is a checked exception. In Java, if a method can throw a checked exception like IOException, it must either handle it with a try-catch block or declare it in the throws clause. This allows the caller to handle the exception appropriately.

Exam trap

The trap here is that candidates often confuse checked and unchecked exceptions, or think that declaring a broader exception like Exception is acceptable, but the exam tests precise exception handling where the exact checked exception must be declared.

How to eliminate wrong answers

Option A is wrong because RuntimeException is an unchecked exception; declaring it in the throws clause is unnecessary and does not satisfy the requirement to declare the checked IOException. Option B is wrong because while Exception is a superclass of IOException, it is too broad and would catch all checked exceptions, which is not the precise declaration needed for IOException. Option C is wrong because it assumes the exception is handled internally with a try-catch, but the question states the method 'throws IOException', meaning it must be declared in the throws clause to propagate the exception to the caller.

30
MCQhard

You are responsible for a Java 17 application that processes user uploads. The application uses a custom AutoCloseable resource, UploadSession, which must always be closed after use to free server resources. A junior developer wrote the following code: ``` UploadSession session = new UploadSession(); try { session.upload(data); // more processing } catch (UploadException e) { log.error("Upload failed", e); } finally { session.close(); } ``` During a code review, you notice that the close() method of UploadSession throws a checked CloseException. The current code does not handle this exception. Which course of action should you recommend to ensure the application is robust and follows best practices?

A.Add a try-catch block inside the finally block to handle CloseException from session.close().
B.Declare the method with throws CloseException, and remove the finally block.
C.Keep the code as-is. The CloseException is not critical; it can be ignored.
D.Rewrite the code to use try-with-resources: try (UploadSession session = new UploadSession()) { ... } catch (UploadException e) { ... }
AnswerD

Try-with-resources handles closure automatically and properly suppresses exceptions.

Why this answer

Option D is correct because try-with-resources automatically calls the close() method on the UploadSession resource when the try block exits, whether normally or abruptly. This eliminates the need for an explicit finally block and ensures that any checked exception thrown by close() is either caught or propagated according to the developer's declared exception handling, making the code both robust and concise.

Exam trap

The trap here is that candidates may think a finally block is always necessary for cleanup, but try-with-resources automatically handles resource closure and exception suppression, making it the preferred pattern for AutoCloseable resources.

How to eliminate wrong answers

Option A is wrong because adding a try-catch inside the finally block would swallow the CloseException, potentially hiding resource cleanup failures and violating best practices for exception handling. Option B is wrong because removing the finally block and declaring throws CloseException would leave the session unclosed if an exception occurs before the close() call, defeating the purpose of resource management. Option C is wrong because ignoring a checked exception from close() is not permitted by the Java compiler; the code as written will not compile, and even if it did, ignoring resource cleanup exceptions can lead to resource leaks and data corruption.

31
MCQmedium

A Java application uses a custom resource class implementing AutoCloseable. The close() method throws a checked exception. In a try-with-resources block, if both the try block and the close() method throw exceptions, which exception is propagated to the caller? Assume the resource is declared in try-with-resources.

A.The exception from the try block is the primary exception, and the close() exception is added as a suppressed exception.
B.The exception from close() is always the primary exception.
C.Both exceptions are thrown simultaneously as a multi-catch exception.
D.The exception from the try block is always suppressed.
AnswerA

Correct behavior per Java try-with-resources.

Why this answer

In a try-with-resources block, when both the try block and the close() method throw exceptions, the exception from the try block is the primary exception propagated to the caller. The exception thrown by close() is added to the primary exception's suppressed exception list, as defined by the Java Language Specification (JLS §14.20.3.2). This ensures that the most relevant exception (the one from the application logic) is not masked by a resource-closing failure.

Exam trap

The trap here is that candidates often assume the last exception thrown (from close()) overwrites the first, or that both exceptions are thrown together, when in fact the try block exception is primary and the close() exception is suppressed.

How to eliminate wrong answers

Option B is wrong because the exception from close() is never the primary exception when both the try block and close() throw; the try block exception always takes precedence. Option C is wrong because Java does not support simultaneous multi-catch exceptions; exceptions are sequential, and only one is propagated with others suppressed. Option D is wrong because the exception from the try block is the primary exception, not suppressed; it is the close() exception that is suppressed.

32
Multi-Selecteasy

Which TWO statements about the try-with-resources statement are true? (Choose two.)

Select 2 answers
A.The resources must implement the Closeable interface.
B.Resources can be reassigned inside the try block.
C.Resources declared in the try-with-resources block are closed automatically.
D.Resources are closed in the reverse order of their declaration.
E.Multiple resources are separated by commas.
AnswersC, D

Correct: The try-with-resources statement ensures each resource is closed at the end of the statement.

Why this answer

Option C is correct because the try-with-resources statement automatically closes each resource declared in the resource specification after the try block completes, whether normally or abruptly. This is the primary purpose of the construct: to ensure reliable resource cleanup without requiring an explicit finally block.

Exam trap

The trap here is that candidates often confuse the required interface (AutoCloseable vs. Closeable) and the separator between multiple resources (semicolons vs. commas), leading them to select the plausible-sounding but incorrect options A and E.

33
Multi-Selecthard

Which TWO are valid multi-catch statements in Java 17? (Choose two.)

Select 2 answers
A.catch (SQLException | IOException e)
B.catch (Exception | RuntimeException e)
C.catch (SQLException | Exception e)
D.catch (IOException | FileNotFoundException e)
E.catch (IOException | RuntimeException e)
AnswersA, E

Valid; they are unrelated.

Why this answer

Option A is correct because Java 17 allows a multi-catch clause to handle multiple exception types in a single catch block, provided the exception types are unrelated in the class hierarchy. SQLException and IOException are both checked exceptions that do not inherit from each other, so they can be caught together in a multi-catch statement.

Exam trap

The trap here is that candidates often forget the rule that multi-catch types must be unrelated in the class hierarchy, leading them to incorrectly select options that include a parent and child exception (like Exception and RuntimeException) or a subclass and its superclass (like IOException and FileNotFoundException).

34
MCQmedium

Consider the following code snippet: try { // some code } catch (IOException e) { // handle } catch (FileNotFoundException e) { // Line X // handle } What will be the result?

A.The code compiles and runs without issues.
B.The code compiles but throws a ClassCastException at runtime.
C.The code compiles but the second catch never executes.
D.Compilation fails at Line X with an error about an exception already caught.
AnswerD

Correct: FileNotFoundException is already caught by IOException.

Why this answer

Option D is correct because in Java, when catching exceptions, the more specific exception subclass must be caught before the more general superclass. FileNotFoundException is a subclass of IOException, so catching IOException first makes the catch for FileNotFoundException unreachable, causing a compilation error at Line X.

Exam trap

The trap here is that candidates may think the code compiles and the second catch simply never runs, but Java enforces this at compile time to prevent unreachable code, not just at runtime.

How to eliminate wrong answers

Option A is wrong because the code does not compile due to the order of catch blocks. Option B is wrong because the code fails to compile, so no runtime exception like ClassCastException can occur. Option C is wrong because the code does not compile; the second catch block is not merely unreachable at runtime but causes a compile-time error.

35
MCQeasy

Which of the following is a checked exception in Java?

A.NullPointerException
B.ArithmeticException
C.IOException
D.IllegalArgumentException
AnswerC

Checked exception, must be handled or declared.

Why this answer

Option C is correct because IOException is a checked exception in Java. Checked exceptions are subclasses of Exception (excluding RuntimeException and its subclasses), and the compiler enforces that they are either caught or declared in the method's throws clause. IOException directly extends Exception, making it a checked exception that must be handled at compile time.

Exam trap

The trap here is that candidates often confuse any exception that occurs at runtime with a 'checked exception', forgetting that only subclasses of Exception that are not subclasses of RuntimeException are checked, so they incorrectly select NullPointerException or ArithmeticException.

How to eliminate wrong answers

Option A is wrong because NullPointerException extends RuntimeException, making it an unchecked exception; the compiler does not require it to be caught or declared. Option B is wrong because ArithmeticException also extends RuntimeException, so it is an unchecked exception that can occur at runtime without mandatory handling. Option D is wrong because IllegalArgumentException extends RuntimeException, thus it is an unchecked exception and does not need to be declared or caught.

36
MCQeasy

Given the code in the exhibit, which of the following is true about this custom exception?

A.It cannot be used with multi-catch because it is unchecked.
B.It is an unchecked exception.
C.It must be caught or declared in the method signature.
D.It must implement the Serializable interface.
AnswerB

Extends RuntimeException.

Why this answer

Option B is correct because the custom exception extends RuntimeException, which makes it an unchecked exception. Unchecked exceptions do not require handling or declaration in the method signature, and they can be used in multi-catch blocks.

Exam trap

Oracle often tests the misconception that all custom exceptions must be checked exceptions, but the trap here is that a custom exception extending RuntimeException is unchecked, so it does not require handling or declaration, and it can still be used in multi-catch blocks.

How to eliminate wrong answers

Option A is wrong because unchecked exceptions can be used with multi-catch; multi-catch works with any exception type, checked or unchecked, as long as the types are not in the same inheritance hierarchy. Option C is wrong because unchecked exceptions (subclasses of RuntimeException) do not need to be caught or declared in the method signature; only checked exceptions have that requirement. Option D is wrong because implementing Serializable is not a requirement for custom exceptions; it is optional and only relevant if the exception needs to be serialized (e.g., for remote method invocation).

37
MCQmedium

Which of the following is a best practice when creating a custom exception class?

A.Implement the Exception interface.
B.Extend Error to indicate a serious system error.
C.Extend RuntimeException for an unchecked exception.
D.Extend Throwable directly to create a new exception type.
AnswerC

Standard practice for custom exceptions that represent programming errors.

Why this answer

Option C is correct because extending RuntimeException is the standard way to create a custom unchecked exception in Java. Unchecked exceptions do not require explicit handling via try-catch or throws clauses, making them suitable for programming errors like invalid arguments or illegal states. This aligns with Java's exception hierarchy where RuntimeException and its subclasses are unchecked.

Exam trap

The trap here is that candidates may think extending Throwable directly is acceptable for creating a new exception type, but the Java Language Specification recommends extending Exception or RuntimeException to maintain consistency with the standard hierarchy and avoid confusing checked/unchecked semantics.

How to eliminate wrong answers

Option A is wrong because Exception is a class, not an interface; Java does not have an 'Exception interface' to implement. Option B is wrong because extending Error is reserved for serious system failures (e.g., OutOfMemoryError) that applications should not attempt to handle or create custom subclasses of. Option D is wrong because extending Throwable directly is discouraged; it bypasses the established Exception and Error hierarchy, leading to non-standard exception types that are neither checked nor unchecked in a conventional sense.

38
MCQmedium

A developer is writing a method that reads a file and processes its content. The method must ensure that if an IOException occurs during reading, the method throws a custom ApplicationException that wraps the original IOException, and that any resources opened are closed properly. Which approach correctly implements this requirement?

A.try { ... } catch (IOException e) { System.err.println(e); } finally { reader.close(); }
B.catch (Exception e) { throw new ApplicationException(e); } finally { reader.close(); }
C.try (BufferedReader reader = Files.newBufferedReader(path)) { ... } catch (IOException e) { throw new ApplicationException(e); }
D.try { ... reader.close(); } catch (IOException e) { throw new ApplicationException(e); }
AnswerC

Uses try-with-resources for automatic closure and wraps only IOException.

Why this answer

Option C is correct because it uses a try-with-resources statement, which automatically closes the BufferedReader (which implements AutoCloseable) when the block exits, whether normally or exceptionally. The catch clause then catches any IOException and wraps it in a custom ApplicationException, satisfying both the resource-closing and exception-wrapping requirements without manual cleanup.

Exam trap

The trap here is that candidates often think a finally block is required for resource cleanup, but the try-with-resources statement handles it automatically, and they may overlook that placing close() in the try block (as in D) does not guarantee execution if an exception occurs before that line.

How to eliminate wrong answers

Option A is wrong because it only prints the IOException to stderr instead of wrapping it in an ApplicationException, and it manually closes the reader in a finally block, which is error-prone if reader is null or close() throws another exception. Option B is wrong because it catches Exception (too broad) and lacks a try block, making it syntactically invalid; also, it does not ensure resources are closed properly. Option D is wrong because it places reader.close() inside the try block before the catch, meaning if an IOException occurs during reading, close() may not be executed, and if close() itself throws an IOException, it is not handled correctly.

39
MCQmedium

A developer is implementing a method that reads a file and parses its contents. The method should ensure that any resources opened during the process are properly closed, even if an exception occurs. Which approach guarantees resource closure with minimal code?

A.Use try-with-resources with the resource declared in the try clause.
B.Use a try-catch block and close the resource inside the catch block.
C.Use a try block followed by a finally block without catch.
D.Use a try-catch-finally block and call close() in the finally block.
AnswerA

Try-with-resources ensures automatic closure regardless of exceptions.

Why this answer

Option A is correct because try-with-resources automatically closes any resource that implements `AutoCloseable` (or `Closeable`) at the end of the try block, regardless of whether an exception occurs. This guarantees resource closure with minimal code, as the developer does not need to write explicit `close()` calls or manage finally blocks.

Exam trap

The trap here is that candidates may think a finally block is always required for resource cleanup, but try-with-resources implicitly provides that guarantee with less code and better exception handling, making it the preferred approach in modern Java.

How to eliminate wrong answers

Option B is wrong because closing the resource inside the catch block only happens if an exception is caught; if no exception occurs, the resource is never closed, leading to a resource leak. Option C is wrong because a try-finally block without catch requires the developer to manually call `close()` in the finally block, which is more verbose and error-prone than try-with-resources. Option D is wrong because a try-catch-finally block with `close()` in the finally block is a valid approach but requires more boilerplate code and does not guarantee closure if `close()` itself throws an exception (unless nested try-catch is used), whereas try-with-resources handles that automatically.

40
Matchingmedium

Match each JDBC type to its corresponding Java type.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

String

int

long

boolean

java.sql.Timestamp

Why these pairings

JDBC defines mappings between SQL types and Java types.

41
MCQmedium

What is the result when the main method is executed?

A.Both B and C are printed and the program terminates.
B.B is printed and the program terminates.
C.C is printed and the program terminates.
D.A is printed and the program terminates.
AnswerC

Finally block's exception replaces the catch block's exception.

Why this answer

The correct answer is C because the code demonstrates that when an exception is thrown in a try block, the corresponding catch block for that exception type is executed, and then the finally block runs. After the finally block completes, the program terminates normally. In this case, the try block throws an ArithmeticException, which is caught by the catch block that prints 'C', and then the finally block executes but does not change the output.

Exam trap

The trap here is that candidates often mistakenly think that the finally block always prints something or that the catch block for a broader exception (like Exception) will execute, but the specific exception type (ArithmeticException) is matched first, and the finally block does not alter the flow unless it contains a return or throw statement.

How to eliminate wrong answers

Option A is wrong because both 'B' and 'C' are not printed; only the catch block for the specific exception type (ArithmeticException) executes, and the finally block does not print anything in this code. Option B is wrong because 'B' is not printed; the code in the try block after the division by zero is never reached, and the catch block for ArithmeticException prints 'C' instead. Option D is wrong because 'A' is never printed; the try block throws an exception before reaching any print statement for 'A', and the catch block handles the exception.

42
Multi-Selectmedium

Which TWO statements about try-with-resources are correct? (Choose two.)

Select 2 answers
A.Resources are closed in the reverse order of their declaration.
B.Resources are closed in the same order as their declaration.
C.Resources declared in try-with-resources must implement the Closeable interface.
D.Resources declared earlier in the try clause are closed first.
E.If an exception is thrown from the try block and another from a resource's close() method, the try block exception propagates and the close() exception is added as a suppressed exception.
AnswersA, E

Correct; last declared resource closed first.

Why this answer

Option A is correct because the Java Language Specification (JLS §14.20.3) mandates that resources declared in a try-with-resources statement are closed in the reverse order of their declaration. This ensures that if a resource depends on another declared earlier, the dependent resource is closed first, preventing resource leaks or inconsistent states.

Exam trap

The trap here is that candidates often confuse the closing order with declaration order or mistakenly think `Closeable` is required instead of `AutoCloseable`, leading them to select options B or C.

43
MCQhard

In the exhibit, if an IOException occurs during closing of both resources, which resource's close exception is returned by e.getSuppressed()?

A.The suppressed array contains both exceptions.
B.Only the exception from FileInputStream close is in the suppressed array.
C.The suppressed array contains the exception from FileInputStream.
D.Only the exception from BufferedInputStream close is in the suppressed array.
AnswerC

BufferedInputStream closed first; its exception is primary, FileInputStream's exception is added to suppressed.

Why this answer

The primary exception is from the try block (if any) or from the first resource close. Since no exception in try block, the first close (bis) throws primary exception? Actually with try-with-resources, if no exception in try, the first exception encountered during close becomes primary. Resources closed in reverse order: bis first, then fis.

If both throw, bis exception is primary, fis exception is suppressed. Option B is correct.

44
MCQmedium

Consider the following code: public void process() throws Exception { try { riskyMethod(); } catch (IOException | SQLException e) { throw e; } } Assuming riskyMethod() declares both IOException and SQLException, what is the result?

A.Compilation fails because you cannot rethrow a multi-catch variable.
B.Compilation fails because the catch variable must be cast to Exception.
C.The code compiles, but throws a ClassCastException at runtime.
D.The code compiles and runs correctly.
AnswerD

Works fine in Java 17.

Why this answer

In Java 7+, multi-catch variables are implicitly final, so they can be rethrown without a cast. The compiler knows that the thrown exception is exactly one of the caught types (IOException or SQLException), and since both are checked exceptions declared in the method signature, the code compiles and runs correctly. Option D is correct.

Exam trap

The trap here is that candidates mistakenly believe multi-catch variables cannot be rethrown without a cast, confusing them with pre-Java 7 single-catch blocks where the variable was not effectively final.

How to eliminate wrong answers

Option A is wrong because a multi-catch variable is effectively final and can be rethrown directly; the compiler does not require a cast. Option B is wrong because no cast to Exception is needed; the rethrown exception is already compatible with the method's throws clause. Option C is wrong because no ClassCastException occurs at runtime; the rethrow preserves the exact exception type.

45
MCQhard

You are developing a microservice that processes order payments. The service uses a custom exception hierarchy: PaymentException (checked), InsufficientFundsException (unchecked, extends RuntimeException), and NetworkException (checked, extends PaymentException). The processPayment method is declared as: public void processPayment(Order order) throws PaymentException. Inside, a call to an external payment gateway may throw InsufficientFundsException or NetworkException. The requirement is to log all payment failures to an audit system, but the service must continue processing other orders. The audit logging method is: public void logFailure(String message) throws Exception. Which approach best handles exceptions while meeting the requirements?

A.Wrap the call to the payment gateway in a try-catch-finally block. In the catch block, log the error using logFailure. In the finally block, return from the method.
B.Add a throws clause to processPayment for InsufficientFundsException and NetworkException, and let the caller handle them.
C.Catch InsufficientFundsException and NetworkException in separate catch blocks. Inside each, try to call logFailure; if logFailure throws an exception, catch it and log a generic message to a fallback logger. Then return normally from processPayment without throwing.
D.Catch InsufficientFundsException and NetworkException separately, log the error using logFailure, and then throw a new RuntimeException to indicate failure.
AnswerC

Correct: This handles all exceptions, logs the failure, and allows the method to return normally so the service continues.

Why this answer

Option C is correct because it ensures that both checked (NetworkException) and unchecked (InsufficientFundsException) exceptions are caught locally, allowing the service to log the failure via logFailure (which itself throws Exception) without propagating the exception up the call stack. By catching any exception from logFailure and falling back to a generic logger, the method guarantees that processPayment returns normally, meeting the requirement to continue processing other orders. This approach respects the checked exception contract of processPayment (throws PaymentException) while handling all failure scenarios internally.

Exam trap

The trap here is that candidates often think they must either propagate all exceptions (option B) or convert them to runtime exceptions (option D), but the requirement to 'continue processing other orders' means the method must not throw any exception after logging, which is achieved by catching all exceptions locally and ensuring the method returns normally.

How to eliminate wrong answers

Option A is wrong because returning from the finally block will suppress any exception thrown in the catch block (including from logFailure), but it does not handle the case where logFailure itself throws an exception, and it incorrectly returns from the method without ensuring the original exception is properly logged or suppressed. Option B is wrong because adding throws clauses for InsufficientFundsException and NetworkException would force the caller to handle these exceptions, violating the requirement that the service itself must continue processing other orders without propagating failures. Option D is wrong because throwing a new RuntimeException after logging would cause the exception to propagate to the caller, preventing the service from continuing to process other orders, and it does not handle the case where logFailure throws an exception.

46
MCQmedium

A company has a service layer with a method performOperation() that originally declared throws BaseException (a checked exception). Several client methods call performOperation() and catch BaseException, wrapping it in a RuntimeException for propagation. After a system upgrade, the implementation of performOperation() now explicitly throws two new checked exceptions: SubException1 and SubException2, both of which extend BaseException. The client methods must continue to compile without modifying their catch signatures, and they must still handle the new exceptions appropriately. What is the best way to modify the client methods?

A.Use a multi-catch block to catch SubException1 and SubException2 and rethrow as RuntimeException.
B.Modify the client method signature to declare throws SubException1, SubException2.
C.Add separate catch blocks for SubException1 and SubException2 before the existing BaseException catch.
D.No change needed because the catch for BaseException catches all subclasses.
AnswerD

Polymorphism applies; no modification required.

Why this answer

Option D is correct because in Java, a catch block for a superclass exception type (BaseException) will catch all subclasses (SubException1 and SubException2) due to polymorphism in exception handling. Since the client methods already catch BaseException and wrap it in a RuntimeException, no changes are needed to the catch signatures; the new exceptions are automatically handled. This satisfies the requirement that client methods continue to compile without modifying their catch signatures while still handling the new exceptions appropriately.

Exam trap

The trap here is that candidates often think they must explicitly catch new subclasses or use multi-catch, forgetting that a catch for the superclass already covers all subclasses due to polymorphism in exception handling.

How to eliminate wrong answers

Option A is wrong because adding a multi-catch block for SubException1 and SubException2 would require modifying the catch signatures, which violates the requirement that client methods must continue to compile without modifying their catch signatures. Option B is wrong because modifying the client method signature to declare throws SubException1, SubException2 would change the method contract and require all callers to handle these exceptions, which is unnecessary and violates the requirement to keep client methods unchanged. Option C is wrong because adding separate catch blocks for SubException1 and SubException2 before the existing BaseException catch would modify the catch structure, which is not allowed per the requirement; the existing BaseException catch already handles all subclasses, making additional catch blocks redundant and a violation of the 'no modification' constraint.

47
Multi-Selectmedium

Which two statements about multi-catch blocks are correct?

Select 2 answers
A.A multi-catch block cannot catch both checked and unchecked exceptions.
B.A multi-catch block can be used with a finally block.
C.The variable in a multi-catch block is not implicitly final.
D.A multi-catch block can only be used with try-with-resources.
E.The exception types in a multi-catch block must be disjoint.
AnswersB, E

A try statement can have multi-catch and finally.

Why this answer

Option B is correct because the exception types in a multi-catch block must be disjoint (no subtype relationship). Option D is correct because a multi-catch block can be combined with a finally block. Option A is wrong because multi-catch can catch both checked and unchecked exceptions.

Option C is wrong because the variable in a multi-catch block is implicitly final. Option E is wrong because multi-catch can be used with any try, not only try-with-resources.

48
MCQmedium

A developer wants to ensure that a block of code always executes regardless of whether an exception occurs or not, and that any exception thrown in the block is not swallowed. Which construct should be used?

A.try-catch with empty catch block
B.try-catch-finally with catch that rethrows the exception
C.try-finally
D.try-with-resources without catch
AnswerC

Finally runs always; exception propagates uncaught.

Why this answer

The try-finally construct ensures that the finally block always executes after the try block, regardless of whether an exception occurs, and it does not catch or swallow any exception. This meets the requirement of guaranteed execution without suppressing the exception, as the exception propagates up the call stack.

Exam trap

The trap here is that candidates often think a catch block is required to handle exceptions, but the question specifically demands that the exception not be swallowed, making try-finally the correct choice because it executes cleanup code without interfering with exception propagation.

How to eliminate wrong answers

Option A is wrong because an empty catch block swallows the exception, preventing it from propagating, which violates the requirement that the exception not be swallowed. Option B is wrong because while a catch block that rethrows the exception preserves the exception, the finally block still executes, but the catch block itself is unnecessary for the requirement and adds complexity; the question asks for a construct that ensures execution without swallowing, and try-finally alone suffices. Option D is wrong because try-with-resources without a catch will close resources automatically but does not include a finally block; if an exception occurs, the resource closing mechanism may suppress exceptions (via suppressed exceptions), potentially swallowing the primary exception, and there is no guarantee of unconditional code execution after the try block.

49
MCQmedium

What is the result of executing the code in the exhibit?

A.The code compiles and prints 'Caught in main: IOException' because the compiler uses improved rethrow analysis.
B.Prints: Caught in main: Exception
C.The code does not compile because methodA does not declare that it throws Exception.
D.Prints: Caught in main: IOException
AnswerC

The catch parameter is Exception, so rethrow is considered as throwing Exception, which is not declared.

Why this answer

The code does not compile because methodA explicitly throws an IOException, but the catch block in main catches Exception (a broader type). However, the compiler performs improved rethrow analysis only when the exception parameter is effectively final and the catch block is multi-catch or rethrows a checked exception that is declared in the method signature. Here, methodA does not declare that it throws Exception, and the catch block catches Exception, which is not a declared exception in methodA's throws clause, causing a compilation error.

Exam trap

The trap here is that candidates assume improved rethrow analysis allows catching a broader exception type (Exception) without the method declaring it, forgetting that the method's throws clause must still declare the caught exception or the catch block must match the thrown exception exactly.

How to eliminate wrong answers

Option A is wrong because improved rethrow analysis applies only when the caught exception parameter is effectively final and the method declares the specific exception types; here, methodA does not declare Exception, so the compiler cannot infer that IOException is the only exception thrown. Option B is wrong because the code does not compile, so it cannot print 'Caught in main: Exception'. Option D is wrong because the code does not compile, so it cannot print 'Caught in main: IOException'.

Ready to test yourself?

Try a timed practice session using only Java Exceptions questions.