Java Lambda Expression and Exceptions

Introduction

A lambda expression can throw an exception.

If lambda expression throws a checked exception, the exception must be compatible with the exception listed in the throws clause of the abstract method in the functional interface.

// Throw an exception from a lambda expression.  
interface MyFunc {
  double func(double[] n) throws MyException;
}

class MyException extends Exception {
  MyException() {//from  ww  w.j ava2 s .com
    super("Array Empty");
  }
}

public class Main {

  public static void main(String args[]) throws MyException {
    double[] values = { 1.0, 2.0, 3.0, 4.0 };

    // This block lambda computes the average of an array of doubles.
    MyFunc average = (n) -> {
      double sum = 0;

      if (n.length == 0)
        throw new MyException();

      for (int i = 0; i < n.length; i++)
        sum += n[i];

      return sum / n.length;
    };

    System.out.println("The average is " + average.func(values));
    System.out.println("The average is " + average.func(new double[0]));
  }
}



PreviousNext

Related