forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallsToSystemExit.java
More file actions
45 lines (42 loc) · 1.21 KB
/
CallsToSystemExit.java
File metadata and controls
45 lines (42 loc) · 1.21 KB
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
// Problem 1: Miss out cleanup code
class FileOutput {
boolean write(String[] s) {
try {
output.write(s.getBytes());
} catch (IOException e) {
System.exit(1); // BAD: Should handle or propagate error instead of exiting
}
return true;
}
}
// Problem 2: Make code reuse difficult
class Action {
public void run() {
// ...
// Perform tasks ...
// ...
System.exit(0); // BAD: Should return status or throw exception
}
public static void main(String[] args) {
new Action().run();
}
}
// Good example: Proper error handling
class BetterAction {
public int run() throws Exception {
// ...
// Perform tasks ...
// ...
return 0; // Return status instead of calling System.exit
}
public static void main(String[] args) {
try {
BetterAction action = new BetterAction();
int exitCode = action.run();
System.exit(exitCode); // GOOD: Exit from main method
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.exit(1); // GOOD: Exit from main method on error
}
}
}