2

In Java8, I have noticed that exception handling is mandatory while using streams if there is any exception occurs. The exception won't be thrown back to the caller automatically. Is there any option available in java where the exception will be thrown back to the caller or is there any reason why is it mandatory ?

Here is the sample example that explains.

package com.nagra.java8examples;

import java.util.Arrays;
import java.util.List;

public class Java8LambdaExample {

    private static List<String> usersList = Arrays.asList(new String[] {"user1", "user2", "user3"});

    public static void main(String[] args) {
        String sampleUser = "user10";
        try {
            findUser(sampleUser, usersList);
        } catch (InvalidUserException e) {
            e.printStackTrace();
        }
}

    private static void findUser(String userinput, List<String> usersList2) throws InvalidUserException {
        usersList.stream().forEach(name->{
            verifyUsername(name);// compilation error: Unhandled exception type InvalidUserException
            if(name.equals(userinput))
                System.out.println("User found!");
            }
        );
    }

    public static void verifyUsername(String userName) throws InvalidUserException {
        if(userName==null)
            throw new InvalidUserException("Invalid user name !");
    }

}

In the above program, compiler is giving error at verifyUsername(name) call.

package com.nagra.java8examples;

public class InvalidUserException extends Exception {

    private static final long serialVersionUID = 1L;

    public InvalidUserException() {
        super();
    }

    public InvalidUserException(String msg) {
        super(msg);
        System.out.println(msg);
    }

}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Prasad Revanaki
  • 783
  • 4
  • 10
  • 23
  • I would write it in different way. Without exception in lamba function. But i was closed when I write answer :( – Peter1982 Jun 26 '18 at 18:07

0 Answers0