Skip to content

Commit 01529c3

Browse files
alincojanuadamd1985
authored andcommitted
sneaky throws (eugenp#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
1 parent 7262427 commit 01529c3

4 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.sneakythrows;
2+
3+
import lombok.SneakyThrows;
4+
5+
public class SneakyRunnable implements Runnable {
6+
7+
@SneakyThrows
8+
public void run() {
9+
try {
10+
throw new InterruptedException();
11+
} catch (InterruptedException e) {
12+
e.printStackTrace();
13+
}
14+
}
15+
16+
public static void main(String[] args) {
17+
try {
18+
new SneakyRunnable().run();
19+
} catch (Exception e) {
20+
e.printStackTrace();
21+
}
22+
}
23+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.sneakythrows;
2+
3+
import java.io.IOException;
4+
5+
public class SneakyThrows {
6+
7+
8+
public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
9+
throw (E) e;
10+
}
11+
12+
public static void throwsSneakyIOException() {
13+
sneakyThrow(new IOException("sneaky"));
14+
}
15+
16+
17+
public static void main(String[] args) {
18+
try {
19+
throwsSneakyIOException();
20+
} catch (Exception ex) {
21+
ex.printStackTrace();
22+
}
23+
24+
}
25+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.sneakythrows;
2+
3+
import org.junit.Test;
4+
5+
import static junit.framework.TestCase.assertEquals;
6+
7+
public class SneakyRunnableTest {
8+
9+
@Test
10+
public void whenCallSneakyRunnableMethod_thenThrowException() {
11+
try {
12+
new SneakyRunnable().run();
13+
} catch (Exception e) {
14+
assertEquals(InterruptedException.class, e.getStackTrace());
15+
}
16+
}
17+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.sneakythrows;
2+
3+
import org.junit.Test;
4+
5+
import static junit.framework.TestCase.assertEquals;
6+
7+
public class SneakyThrowsTest {
8+
9+
@Test
10+
public void whenCallSneakyMethod_thenThrowSneakyException() {
11+
try {
12+
SneakyThrows.throwsSneakyIOException();
13+
} catch (Exception ex) {
14+
assertEquals("sneaky", ex.getMessage().toString());
15+
}
16+
}
17+
18+
}

0 commit comments

Comments
 (0)