1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
J.R.
  • 2,335
  • 2
  • 19
  • 21
  • 1
    You may want to read this other question [Checked Exceptions in Lambda Expressions](http://stackoverflow.com/q/14039995/697630). It has a good set of answers, most likely you will find yours there too. – Edwin Dalorzo Dec 17 '14 at 19:52

1 Answers1

4

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • thank you @Sotirios!! This solve my current problem, but I'd like to know if it is possible to raise the exception for the future! – J.R. Dec 16 '14 at 16:12
  • 3
    @J.R. See my most recent edit. The exception is thrown within your lambda body. Unless you `try-catch` it within it, the method must be able to throw it. But throwing it is incompatible with the `Predicate` functional interface. – Sotirios Delimanolis Dec 16 '14 at 16:19