Skip to content

Commit 58595ac

Browse files
authored
Merge pull request eugenp#7630 from rahulgul8/3150
Adding System.exit example
2 parents ef8c875 + 7c4c816 commit 58595ac

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.system.exit;
2+
3+
import java.io.BufferedReader;
4+
import java.io.FileReader;
5+
import java.io.IOException;
6+
7+
public class SystemExitExample {
8+
9+
public void readFile() {
10+
try {
11+
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
12+
System.out.println(br.readLine());
13+
br.close();
14+
} catch (IOException e) {
15+
System.exit(2);
16+
} finally {
17+
System.out.println("Exiting the program");
18+
}
19+
}
20+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.baeldung.system.exit;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.security.Permission;
6+
7+
import org.junit.After;
8+
import org.junit.Before;
9+
import org.junit.Test;
10+
11+
public class SystemExitUnitTest {
12+
13+
protected static class ExitException extends SecurityException {
14+
15+
private static final long serialVersionUID = 1L;
16+
public final int status;
17+
18+
public ExitException(int status) {
19+
this.status = status;
20+
}
21+
}
22+
23+
private static class NoExitSecurityManager extends SecurityManager {
24+
@Override
25+
public void checkPermission(Permission perm) {
26+
}
27+
28+
@Override
29+
public void checkPermission(Permission perm, Object context) {
30+
}
31+
32+
@Override
33+
public void checkExit(int status) {
34+
super.checkExit(status);
35+
throw new ExitException(status);
36+
}
37+
}
38+
39+
private SecurityManager securityManager;
40+
41+
private SystemExitExample example;
42+
43+
@Before
44+
public void setUp() throws Exception {
45+
example = new SystemExitExample();
46+
securityManager = System.getSecurityManager();
47+
System.setSecurityManager(new NoExitSecurityManager());
48+
}
49+
50+
@After
51+
public void tearDown() throws Exception {
52+
System.setSecurityManager(securityManager);
53+
}
54+
55+
@Test
56+
public void testExit() throws Exception {
57+
try {
58+
example.readFile();
59+
} catch (ExitException e) {
60+
assertEquals("Exit status", 2, e.status);
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)