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:
alincojanu 2017-09-02 20:38:04 +03:00 committed by adamd1985
parent 7262427421
commit 01529c3202
4 changed files with 83 additions and 0 deletions

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}

View File

@ -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());
}
}
}

View File

@ -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());
}
}
}