Skip to content

Commit 3dc4d48

Browse files
authored
[impr-invocationTargetEx] invocation ex (eugenp#17270)
1 parent bb3c7c2 commit 3dc4d48

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,46 @@
11
package com.baeldung.reflection.exception.invocationtarget;
22

3-
import static org.junit.jupiter.api.Assertions.assertEquals;
43
import static org.junit.jupiter.api.Assertions.assertThrows;
54

65
import java.lang.reflect.InvocationTargetException;
76
import java.lang.reflect.Method;
87

98
import org.junit.jupiter.api.Test;
9+
import org.slf4j.Logger;
10+
import org.slf4j.LoggerFactory;
1011

1112
public class InvocationTargetUnitTest {
1213

14+
private static final Logger LOG = LoggerFactory.getLogger(InvocationTargetUnitTest.class);
15+
1316
@Test
14-
public void whenCallingMethodThrowsException_thenAssertCauseOfInvocationTargetException() throws Exception {
17+
public void whenCallingMethodThrowsException_thenCorrect() throws Exception {
1518

1619
InvocationTargetExample targetExample = new InvocationTargetExample();
1720
Method method = InvocationTargetExample.class.getMethod("divideByZeroExample");
18-
21+
1922
Exception exception = assertThrows(InvocationTargetException.class, () -> method.invoke(targetExample));
20-
21-
assertEquals(ArithmeticException.class, exception.getCause().getClass());
23+
LOG.error("InvocationTargetException Thrown:", exception);
24+
}
25+
26+
@Test
27+
public void whenCallingMethodThrowsException_thenPrintUnderlyingException() {
28+
try {
29+
InvocationTargetExample targetExample = new InvocationTargetExample();
30+
Method method = InvocationTargetExample.class.getMethod("divideByZeroExample");
31+
method.invoke(targetExample);
32+
} catch (InvocationTargetException e) {
33+
Throwable cause = e.getCause();
34+
if (cause instanceof ArithmeticException) {
35+
// handle ArithmeticException
36+
LOG.error("InvocationTargetException caused by ArithmeticException:", cause);
37+
} else {
38+
// handle other exceptions
39+
LOG.error("The underlying exception of InvocationTargetException:", cause);
40+
}
41+
} catch (NoSuchMethodException | IllegalAccessException e) {
42+
// for simplicity, rethrow reflection exceptions as RuntimeException
43+
throw new RuntimeException(e);
44+
}
2245
}
23-
}
46+
}

0 commit comments

Comments
 (0)