How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?
In other words, I want to make code like this compile:
public List<Class> getClasses() throws ClassNotFoundException {
List<Class> classes =
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(className -> Class.forName(className))
.collect(Collectors.toList());
return classes;
}
This code does not compile, since the Class.forName()
method above throws ClassNotFoundException
, which is checked.
Please note I do NOT want to wrap the checked exception inside a runtime exception and throw the wrapped unchecked exception instead. I want to throw the checked exception itself, and without adding ugly try
/catches
to the stream.
You can!
Extending @marcg 's
UtilException
and addingthrow E
where necessary: this way, the compiler will ask you to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.Instructions: just copy/paste
LambdaExceptionUtil
in your IDE and then use it as shown in the belowLambdaExceptionUtilTest
.Some test to show usage and behaviour:
I wrote a library that extends the Stream API to allow you to throw checked exceptions. It uses Brian Goetz's trick.
Your code would become
I agree with the comments above, in using Stream.map you are limited to implementing Function which doesn't throw Exceptions.
You could however create your own FunctionalInterface that throws as below..
then implement it using Lambdas or references as shown below.