File tree Expand file tree Collapse file tree
main/java/com/baeldung/sneakythrows
test/java/com/baeldung/sneakythrows Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments