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);
}
}