File: UnusedException.md

package info (click to toggle)
error-prone-java 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 15,076 kB
  • sloc: java: 171,398; xml: 1,459; sh: 34; makefile: 7
file content (37 lines) | stat: -rw-r--r-- 986 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Catching an exception and throwing another is a common pattern. This is often
used to supply additional information, or to turn a checked exception into an
unchecked one.

```java
  try {
    ioLogic();
  } catch (IOException e) {
    throw new IllegalStateException(); // BAD
  }
```

Throwing a new exception without supplying the caught one as a cause means the
stack trace will terminate at the `catch` block, which will make debugging a
possible fault in `ioLogic()` far harder than is necessary.

Prefer wrapping the original exception instead,

```java
  try {
    ioLogic();
  } catch (IOException e) {
    throw new IllegalStateException(e); // GOOD
  }
```

Suppress false positives with `@SuppressWarnings("UnusedException")` on the
ignored exception. Consider also adding a comment to explain why the exception
should not be propagated.

```java
  try {
    ...
  } catch (@SuppressWarnings("UnusedException") IOException e) {
    throw new IllegalStateException();
  }
```