From b09da347aa1e426523a81e2c48897502af094472 Mon Sep 17 00:00:00 2001 From: "copybara-service[bot]" <copybara-service[bot]@users.noreply.github.com> Date: Fri, 13 Sep 2024 20:30:21 +0000 Subject: [PATCH] Latest docs on successful build 6665 auto-pushed to gh-pages --- bugpattern/EmptyCatch.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/bugpattern/EmptyCatch.md b/bugpattern/EmptyCatch.md index 6928ad35b45..39f6594c0bc 100644 --- a/bugpattern/EmptyCatch.md +++ b/bugpattern/EmptyCatch.md @@ -12,4 +12,35 @@ To make changes, edit the @BugPattern annotation or the explanation in docs/bugp --> +## The problem +The [Google Java Style Guide ยง6.2][style] 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`][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) { +} +``` + +[style]: https://google.github.io/styleguide/javaguide.html#s6.2-caught-exceptions + +[assertthrows]: https://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertThrows(java.lang.Class,%20org.junit.function.ThrowingRunnable)