Fishbowl

A collection of helper methods for dealing with exceptions in Java 8.

Get Fishbowl · GitHub

The scope of Fishbowl is divided into four sections.

There are two options if a statement inside of a method (may) throw a checked exception that cannot be handled reasonably. The exception can be rethrown and the caller of the current method has to handle it or it can be wrapped with a RuntimeException. Use Fishbowl's method wrapCheckedException for doing this with a single line of code.

Read more …

public void doSomething(InputStream is) {
  //originally both lines can throw an IOException
  int nextByte = wrapCheckedException(() -> is.read());
  wrapCheckedException(() -> is.close());
}

Sometimes exceptions are best handled by returning a default value. This can be done by a single line of code with defaultIfException.

Read more …

public void doSomething() {
  long value = defaultIfException(() -> parseLong("NaN"),
      NumberFormatException.class, 0L);
  //value is 0
}

Sometimes it is appropriate to continue if a void method fails. This can be easily done with ignoreException.

Read more …

public void doSomething() {
  MyWorker worker = new MyWorker();
  ignoreException(() -> worker.doSomethingThatThrowsAnException());
  //the following statement is executed even if worker throws an
  //exception.
  doSomethingElse();
}

Fishbowl makes it possible to use the AAA (Arrange-Act-Assert) pattern for writing tests for code that throws an exception. For that purpose it exposes the exception so that it can be checked by any assertion library.

Read more …

@Test
public void anExceptionIsThrown() {
  String noString = null;
  Throwable exception = exceptionThrownBy(() -> noString.trim());
  assertEquals(NullPointerException.class, exception.getClass());
}