diff --git a/core-java-modules/core-java-os/src/main/java/com/baeldung/system/exit/SystemExitExample.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/system/exit/SystemExitExample.java new file mode 100644 index 0000000000..a9738a0448 --- /dev/null +++ b/core-java-modules/core-java-os/src/main/java/com/baeldung/system/exit/SystemExitExample.java @@ -0,0 +1,20 @@ +package com.baeldung.system.exit; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class SystemExitExample { + + public void readFile() { + try { + BufferedReader br = new BufferedReader(new FileReader("file.txt")); + System.out.println(br.readLine()); + br.close(); + } catch (IOException e) { + System.exit(2); + } finally { + System.out.println("Exiting the program"); + } + } +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java new file mode 100644 index 0000000000..6d5f9c2f34 --- /dev/null +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.system.exit; + +import static org.junit.Assert.assertEquals; + +import java.security.Permission; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SystemExitUnitTest { + + protected static class ExitException extends SecurityException { + + private static final long serialVersionUID = 1L; + public final int status; + + public ExitException(int status) { + this.status = status; + } + } + + private static class NoExitSecurityManager extends SecurityManager { + @Override + public void checkPermission(Permission perm) { + } + + @Override + public void checkPermission(Permission perm, Object context) { + } + + @Override + public void checkExit(int status) { + super.checkExit(status); + throw new ExitException(status); + } + } + + private SecurityManager securityManager; + + private SystemExitExample example; + + @Before + public void setUp() throws Exception { + example = new SystemExitExample(); + securityManager = System.getSecurityManager(); + System.setSecurityManager(new NoExitSecurityManager()); + } + + @After + public void tearDown() throws Exception { + System.setSecurityManager(securityManager); + } + + @Test + public void testExit() throws Exception { + try { + example.readFile(); + } catch (ExitException e) { + assertEquals("Exit status", 2, e.status); + } + } +} \ No newline at end of file