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.
  • 76,217
  • 14
  • 120
  • 142
  • 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
  • what is the reason for having `var s = System.out` ? `s` is never used! (just to ask on StackOverflow?) kind of clear that `Systme.out` is being closed before the `finally` block is executed (at least so it is specified in the [JLS](https://docs.oracle.com/javase/specs/jls/se18/html/jls-14.html#jls-14.20.3.2-210): "*Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.*") – user16320675 Apr 06 '22 at 14:28

0 Answers0