sneaky throws (#2505)
* alin.cojanu25@gmail.com * add junit tests * core-java - sneaky throws * delete project spring_sample_annotations and spring_sample_xml ->not intended for this article
This commit is contained in:
parent
7262427421
commit
01529c3202
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.sneakythrows;
|
||||||
|
|
||||||
|
import lombok.SneakyThrows;
|
||||||
|
|
||||||
|
public class SneakyRunnable implements Runnable {
|
||||||
|
|
||||||
|
@SneakyThrows
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
throw new InterruptedException();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
new SneakyRunnable().run();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.sneakythrows;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class SneakyThrows {
|
||||||
|
|
||||||
|
|
||||||
|
public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
|
||||||
|
throw (E) e;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void throwsSneakyIOException() {
|
||||||
|
sneakyThrow(new IOException("sneaky"));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
throwsSneakyIOException();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.sneakythrows;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static junit.framework.TestCase.assertEquals;
|
||||||
|
|
||||||
|
public class SneakyRunnableTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCallSneakyRunnableMethod_thenThrowException() {
|
||||||
|
try {
|
||||||
|
new SneakyRunnable().run();
|
||||||
|
} catch (Exception e) {
|
||||||
|
assertEquals(InterruptedException.class, e.getStackTrace());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.sneakythrows;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static junit.framework.TestCase.assertEquals;
|
||||||
|
|
||||||
|
public class SneakyThrowsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCallSneakyMethod_thenThrowSneakyException() {
|
||||||
|
try {
|
||||||
|
SneakyThrows.throwsSneakyIOException();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
assertEquals("sneaky", ex.getMessage().toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user