BAEL-3840 Suppressed Exceptions in Java

This commit is contained in:
amdegregorio 2020-02-17 06:36:35 -05:00
parent ffb9e43a11
commit a681588bcc
3 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,13 @@
package com.baeldung.suppressed;
public class ExceptionalResource implements AutoCloseable {
public void processSomething() {
throw new NullPointerException("Thrown from processSomething()");
}
@Override
public void close() throws Exception {
throw new NullPointerException("Thrown from close()");
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.suppressed;
import java.io.FileInputStream;
import java.io.IOException;
public class SuppressedExceptionsDemo {
public static void demoSuppressedException(String filePath) throws IOException {
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(filePath);
} catch (IOException e) {
} finally {
fileIn.close();
}
}
public static void demoAddSuppressedException(String filePath) throws IOException {
Throwable firstException = null;
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(filePath);
} catch (IOException e) {
firstException = e;
} finally {
try {
fileIn.close();
} catch (NullPointerException npe) {
if (firstException != null) {
npe.addSuppressed(firstException);
}
}
}
}
public static void demoExceptionalResource() throws Exception {
try (ExceptionalResource exceptionalResource = new ExceptionalResource()) {
exceptionalResource.processSomething();
}
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.suppressed;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
public class SuppressedExceptionsUnitTest {
@Test(expected = NullPointerException.class)
public void givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException() throws IOException {
SuppressedExceptionsDemo.demoSuppressedException("/non-existent-path/non-existent-file.txt");
}
@Test
public void givenNonExistentFileName_whenAttemptFileOpenStoreSuppressed_thenSuppressedExceptionAvailable() {
try {
SuppressedExceptionsDemo.demoAddSuppressedException("/non-existent-path/non-existent-file.txt");
} catch (Exception e) {
assertEquals(1, e.getSuppressed().length);
assertThat(e.getSuppressed()[0], instanceOf(FileNotFoundException.class));
}
}
@Test
public void whenUsingExceptionalResource_thenSuppressedExceptionAvailable() {
try {
SuppressedExceptionsDemo.demoExceptionalResource();
} catch (Exception e) {
assertEquals("Thrown from processSomething()", e.getMessage());
assertEquals(1, e.getSuppressed().length);
assertEquals("Thrown from close()", e.getSuppressed()[0].getMessage());
}
}
}