File: SystemExitOutsideMain.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 (46 lines) | stat: -rw-r--r-- 979 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
38
39
40
41
42
43
44
45
46
Calling `System.exit` terminates the java process and returns a status code.
Since it is disruptive to shut down the process within library code,
`System.exit` should not be called outside of a main method.

Instead of calling `System.exit` consider throwing an unchecked exception to
signal failure.

For example, prefer this:

```java
public static void main(String[] args) {
  try {
    doSomething(args[0]);
  } catch (MyUncheckedException e) {
    System.err.println(e.getMessage());
    System.exit(1);
  }
}

// In library code
public static void doSomething(String s) {
  try {
    doSomethingElse(s);
  } catch (MyCheckedException e) {
    throw new MyUncheckedException(e);
  }
}
```

to this:

```java
public static void main(String[] args) {
  doSomething(args[0]);
}

// In library code
public static void doSomething(String s) {
  try {
    doSomethingElse(s)
  } catch (MyCheckedException e) {
    System.err.println(e.getMessage());
    System.exit(1);
  }
}
```