public DiskCache(File file, System2 system2) { this.system2 = system2; this.file = file; OutputStream output = null; boolean threw = true; try { // writes the serialization stream header required when calling "traverse()" // on empty stream. Moreover it allows to call multiple times "newAppender()" output = new ObjectOutputStream(new FileOutputStream(file)); output.flush(); threw = false; } catch (IOException e) { throw new IllegalStateException("Fail to write into file: " + file, e); } finally { if (threw) { // do not hide initial exception IOUtils.closeQuietly(output); } else { // raise an exception if can't close system2.close(output); } } }
@Test public void close() { class MyCloseable implements Closeable { boolean isClosed = false; @Override public void close() throws IOException { isClosed = true; } } MyCloseable closeable = new MyCloseable(); System2.INSTANCE.close(closeable); assertThat(closeable.isClosed).isTrue(); }
@Test public void close_throws_exception_on_error() { Closeable closeable = new Closeable() { @Override public void close() throws IOException { throw new IOException("expected"); } }; try { System2.INSTANCE.close(closeable); fail(); } catch (IllegalStateException e) { assertThat(e.getCause().getMessage()).isEqualTo("expected"); } }
public DiskCache(File file, System2 system2) { this.system2 = system2; this.file = file; OutputStream output = null; boolean threw = true; try { // writes the serialization stream header required when calling "traverse()" // on empty stream. Moreover it allows to call multiple times "newAppender()" output = new ObjectOutputStream(new FileOutputStream(file)); output.flush(); threw = false; } catch (IOException e) { throw new IllegalStateException("Fail to write into file: " + file, e); } finally { if (threw) { // do not hide initial exception IOUtils.closeQuietly(output); } else { // raise an exception if can't close system2.close(output); } } }