Please, consider the following code:
class Bum implements AutoCloseable{
public void bu() throws Exception{
System.out.println("Bu");
throw new Exception();
}
@Override
public void close(){
System.out.println("Closed");
}
}
public class TestTryWith {
private static void tryWith(){
try (Bum bum=new Bum()){
bum.bu();
}catch (Exception ex){
System.out.println("Exception");
//ex.printStackTrace();
}
}
private static void tryCatchFinally(){
Bum bum=new Bum();
try{
bum.bu();
}catch (Exception ex){
System.out.println("Exception");
}finally{
bum.close();
}
}
public static void main(String[] args) {
tryCatchFinally();
System.out.println("------------");
tryWith();
}
}
And the output is:
Bu
Exception
Closed
------------
Bu
Closed
Exception
I've read that try-with-resources is converted to try-catch-finally block by the compiler. However, as you see the order is different. When we use try-with-resources the close method is invoked BEFORE the catch clause. Why?