Why Java StringWriter close method throws IOException?

216 Views Asked by At

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 ;-).

0

There are 0 best solutions below