Skip to content

Instantly share code, notes, and snippets.

@VenkataRaju
Created March 16, 2018 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VenkataRaju/5abe22f8652f8fdb4f80bb8c07c5bf6f to your computer and use it in GitHub Desktop.
Save VenkataRaju/5abe22f8652f8fdb4f80bb8c07c5bf6f to your computer and use it in GitHub Desktop.
Throw checked exception without declaring and create useful Stream friendly functional interfaces which throws Exception
public class SneakyThrow
{
public static RuntimeException uncheckedThrow(Throwable t)
{
throw uncheckedThrow0(t);
}
@SuppressWarnings("unchecked")
private static <X extends Throwable> RuntimeException uncheckedThrow0(Throwable t) throws X
{
throw (X) t;
}
public interface CheckedFunction<I, O>
{
public O apply(I i) throws Exception;
}
public static <I, O> Function<I, O> uncheckedFunction(CheckedFunction<I, O> cf)
{
return (I i) ->
{
try
{
return cf.apply(i);
}
catch (Exception e)
{
throw uncheckedThrow(e);
}
};
}
public static void main(String[] args)
{
Path[] paths = {};
Stream.of(paths).flatMap(SneakyThrow.uncheckedFunction(Files::lines));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment