Skip to content

Instantly share code, notes, and snippets.

@jfager
Last active February 18, 2022 06:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfager/9317201 to your computer and use it in GitHub Desktop.
Save jfager/9317201 to your computer and use it in GitHub Desktop.
Java 8 - Wrap Checked Exceptions in RuntimeExceptions Less Verbosely
package scratch.unsafe;
import java.util.Random;
public class Today {
public static void main(String[] args) {
String foo;
try {
if(new Random().nextBoolean()) {
throw new Exception("I force try/catch or a method signature change, I suck.");
} else {
foo = "Cool";
}
} catch(Exception e) {
throw new RuntimeException(e);
}
System.out.println(foo);
try {
throw new Exception("I force try/catch or a method signature change, I suck.");
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
package scratch.unsafe;
import static scratch.unsafe.Util.unsafe;
import java.util.Random;
public class Tomorrow {
public static void main(String[] args) {
String foo = unsafe(() -> {
if(new Random().nextBoolean()) {
throw new Exception("Look ma, no try/catch!");
} else {
return "Cool";
}
});
unsafe(() -> {
throw new Exception("Look ma, no try/catch!");
});
}
}
package scratch.unsafe;
public class Util {
//These can be private and the compiler will still transform conforming lambdas.
//Edit: nm, they fail sometimes. Hrm...
public interface Block {
void go() throws Exception;
}
public interface NoArgFn<T> {
T go() throws Exception;
}
//And because these overload it only looks like I'm importing one name.
public static void unsafe(Block t) {
try {
t.go();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static <T> T unsafe(NoArgFn<T> f) {
try {
return f.go();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment