Last active
February 18, 2022 06:56
-
-
Save jfager/9317201 to your computer and use it in GitHub Desktop.
Java 8 - Wrap Checked Exceptions in RuntimeExceptions Less Verbosely
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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