Back to Error Prone

EmptyCatch

docs/bugpattern/EmptyCatch.md

2.49.0965 B
Original Source

The Google Java Style Guide §6.2 states:

It is very rarely correct to do nothing in response to a caught exception. (Typical responses are to log it, or if it is considered "impossible", rethrow it as an AssertionError.)

When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.

When writing tests that expect an exception to be thrown, prefer using Assert.assertThrows instead of writing a try-catch. That is, prefer this:

java
assertThrows(NoSuchElementException.class, () -> emptyStack.pop());

instead of this:

java
try {
  emptyStack.pop();
  fail();
} catch (NoSuchElementException expected) {
}