Reputation: 2405
I have the follow lambda expression:
public mylambdafunction(){
Optional<MyClass> optional = Arrays.stream(myClassesValues).filter(x ->
new String(x.bytesArray,"UTF-16LE").equalsIgnoreCase(comparationString)).findFirst();
}
Well, the method new String(x.bytesArray,” UTF-16LE”)
raise the Exception UnsupportedEncodingException
.
I’d like to raise the exception to the main function mylambdafunction()
, somethings like:
public mylambdafunction() throws UnsupportedEncodingException{
....
}
Is that possible?
Upvotes: 1
Views: 3855
Reputation: 279930
An alternative to potentially modifying a functional interface method, since you are using a well known character set, is to use the overloaded String
constructor which accepts a byte[]
and a Charset
, but which doesn't throw UnsupportedEncodingException
.
Use StandardCharsets.UTF_16LE
as the Charset
argument.
Stream#filter(Predicate)
expects a Predicate
which provides a test(Object)
method. Since this method does not declare a checked exception which is a supertype of UnsupportedEncodingException
(and since UnsupportedEncodingException
is itself checked), then any lambda expression whose body throws such an exception will be incompatible. Similarly, any method reference to a method that declares such an exception will also be incompatible.
Upvotes: 4