Quote from the JLS section 14.20.3.1 :
In the core try-with-resources application managing a single resource:
This means that if both codes inside the try block and the automatic close() operator throw an exception, the catch part will handle the exception thrown by the try block, except that close() is thrown in the suppressed exceptions .
In addition, this means that if the try block is successful, but the automatic close() fails, the catch will be executed, and the exception thrown for the exception will be the exception thrown by close() .
Here we check the verification of this behavior:
public class Main { public static void main(String[] args) throws Exception {
This code will print
thrown by try part thrown by close thrown by close
which means that the exception thrown for the exception was thrown by the try part for the code for the first part. For the second part, the exception clamped in the list was indeed the exception caused by close() .
source share