在Java8中,我注意到,如果发生任何异常,则在使用流时必须对异常进行处理。异常不会自动抛出给调用者。在Java中是否有任何可用的选项可以将异常抛出给调用者,或者是否有任何强制执行此异常的原因?
这是说明示例。
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 !");
}
}
在上述程序中,编译器在verifyUsername(name)调用时给出错误。
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);
}
}