1

I wonder why Java designers made close() method on StringWriter throwing the IOException, when it actually does nothing. E.g. in PrintWriter, the exceptions are suppressed even though the PrintWriter really can do something when it uses an appropriate Writer. Wouldn't it make sense to make StringWriter.close method throwing nothing? Or does current solution have some reason?

Motivation:

try (final StringWriter stringWriter = new StringWriter();
     final PrintWriter printWriter = new PrintWriter(stringWriter);
){
    // ...
}

I have to handle IOException since the close method is being to be called by the try-with-resources block. Of course I can place StringWriter before the try-with-resources block, but why to do it since it's an autocloseable ;-).

Mi-La
  • 685
  • 10
  • 18
  • I _feel_ like overriding methods _used to_ have to keep the exceptions thrown by the overridden method in their own signatures, and that this only became optional afterwards, but I can't manage to confirm my guess. But yeah, I'd say that this is so because of legacy :) – sp00m May 05 '22 at 10:23

0 Answers0