1

When I run this code, finally block does not execute. If I change System.out to System.err in try block, it works. Or when I change out to err in finally block it works. What is the reason?

Thanks in advance for answer!

    String fn = "data.txt";

try (var w = new BufferedWriter(new FileWriter(fn)); var s = System.out) {

    w.write("Hi, there!");

    w.flush();

    w.write('!');

    System.out.print("1");

} catch (IOException e) {

    System.out.print("2");

} finally {

    System.out.print("3");

}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 5
    Because you're closing `System.out` by using it with `try-with-resources`. – Kayaman Apr 06 '22 at 14:16
  • 1
    You are using try-with-resources: try (... var s = System.out) { ... } catch (IOException e) { System.out.print("2"); } finally { System.out.print("3"); } This causes any variables declared within brackets right after try to be automatically closed after termination of the try block. The finally block is actually being executed, but you don't see the output because System.out has been closed. – Adriaan Koster Apr 06 '22 at 14:20
  • Even if you weren't closing `System.out` by accident, `System.out` is not guaranteed to flush out unless you output a newline or call `flush()`. You are not doing either of those things. See https://stackoverflow.com/a/7166357/139985 – Stephen C Apr 06 '22 at 14:26

0 Answers0