Senior
If an exception occurs both in try and when closing the resource (try-with-resources), what will catch?
sobes.tech AI
Answer from AI
If an exception occurs in the try block, and another exception occurs when closing the resource in try-with-resources, then the exception from the try block will be caught in the catch, and the exception that occurred during resource closing will be suppressed and accessible via the Throwable.getSuppressed() method on the main exception.
Example:
try (MyResource res = new MyResource()) {
throw new IOException("Error in try");
} catch (IOException e) {
System.out.println("Main exception: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("Suppressed exception: " + suppressed.getMessage());
}
}
In this example, the "Error in try" exception will be caught in the catch, and the exception that occurred during resource closing will be suppressed and accessible via getSuppressed().