Illuminatiiiiii
11/11/2018 - 6:48 PM

Lambdas with Exceptions

For Episode 65 of the Java Series: https://youtu.be/LLuMW6d9z6I

interface NumbersFunction{
    double func(int[] array) throws EmptyArrayException; //Added an exception to function
}

//Creating our custom exception
class EmptyArrayException extends Exception{
    EmptyArrayException(){
        super("Array is empty");
    }
}

public class Main {

    public static void main(String[] args) throws EmptyArrayException {

        int[] numbers = {1, 5, 2, 60, 2000, 11, 54, 2};
        int[] numbers2 = {};

        NumbersFunction highestNum = (int[] a) -> {
            if (a.length == 0){
                throw new EmptyArrayException();
            }else{
                int highestNumber = 1;
                for (int i = 0; i < a.length;i++){
                    if (a[i] > highestNumber){
                        highestNumber = a[i];
                    }
                }
                return highestNumber;
            }
        };
        System.out.println(highestNum.func(numbers));
        System.out.println(highestNum.func(numbers2)); //Throws exception

    }
}