File: CatchFail.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (43 lines) | stat: -rw-r--r-- 883 bytes parent folder | download | duplicates (2)
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
38
39
40
41
42
43
Ignoring an exception and calling `fail()` is unnecessary, since an uncaught
exception will already cause a test to fail. It also makes the test output less
useful, since the exception's message and stack trace is lost.

Do this:

```java
@Test
public void testFoo() throws Exception {
   int x = foos(); // the test fails if this throws
   assertThat(x).isEqualTo(42);
}
```

or this:

```java
@Test
public void testFoo() throws Exception {
   int x;
   try {
     x = foos();
   } catch (Exception e) {
     throw new AssertionError("the test failed", e); // wraps the exception with additional context
   }
   assertThat(x).isEqualTo(42);
}
```

Not this:

```java
@Test
public void testFoo() {
   int x;
   try {
     x = foos();
   } catch (Exception e) {
     fail("the test failed"); // the exception message and stack trace is lost
   }
   assertThat(x).isEqualTo(42);
}
```