Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何处理ifPresent内部的异常?_Java_Exception_Java 8_Java Stream_Optional - Fatal编程技术网

Java 如何处理ifPresent内部的异常?

Java 如何处理ifPresent内部的异常?,java,exception,java-8,java-stream,optional,Java,Exception,Java 8,Java Stream,Optional,在方法内部,需要一个条件来继续逻辑。“我的IDE”中将显示未处理的异常警告消息。用try-catch包装整个块不会让消息消失 public void changePassword(String login, String currentClearTextPassword, String newPassword) { userRepository.findOneByLogin(login) .ifPresent(user -> {

在方法内部,需要一个条件来继续逻辑。“我的IDE”中将显示未处理的异常警告消息。用try-catch包装整个块不会让消息消失

public void changePassword(String login, String currentClearTextPassword, String newPassword) {

    userRepository.findOneByLogin(login)
            .ifPresent(user -> {
                String currentEncryptedPassword = user.getUserSecret();
                String encryptedInputPassword = "";
                try {
                    encryptedInputPassword = authUtils.encrypt(currentClearTextPassword);
                } catch (Exception ex) {
                    System.err.println("Encryption exception: " + ex.getMessage());
                }
                if (!Objects.equals(encryptedInputPassword, currentEncryptedPassword)) {
                    throw new Exception("Invalid Password");  // <-- unhandled exception
                }
                String encryptedNewPassword = "";
                try {
                    encryptedNewPassword = authUtils.encrypt(newPassword);
                } catch (Exception ex) {
                    System.err.println("Encryption exception: " + ex.getMessage());
                }
                user.setUserSecret(encryptedNewPassword);
                userRepository.save(user);
                log.debug("Changed password for User: {}", user);
            });
}
public void changePassword(字符串登录、字符串currentClearTextPassword、字符串newPassword){
userRepository.findOneByLogin(登录)
.ifPresent(用户->{
字符串currentEncryptedPassword=user.getUserSecret();
字符串encryptedInputPassword=“”;
试一试{
encryptedInputPassword=authUtils.encrypt(currentClearTextPassword);
}捕获(例外情况除外){
System.err.println(“加密异常:+ex.getMessage());
}
如果(!Objects.equals(encryptedInputPassword,currentEncryptedPassword)){

抛出新异常(“无效密码”);//在流操作中处理异常会有一点开销,我想将该操作分开,如下所示:

public void changePassword(String login, String currentClearTextPassword, String newPassword) throws Exception {
    //get the user in Optional
    Optional<User> check = userRepository.findOneByLogin(login);

    //if the user is present 'isPresent()'
    if(check.isPresent()){

        //get the user from the Optional and do your actions
        User user = check.get();

        String currentEncryptedPassword = user.getUserSecret();
        String encryptedInputPassword = "";
        try {
            encryptedInputPassword = authUtils.encrypt(currentClearTextPassword);
        } catch (Exception ex) {
            throw new Exception("Encryption exception: " + ex.getMessage());
        }
        if (!Objects.equals(encryptedInputPassword, currentEncryptedPassword)) {
            throw new Exception("Invalid Password");  // <-- unhandled exception
        }
        String encryptedNewPassword = "";
        try {
            encryptedNewPassword = authUtils.encrypt(newPassword);
        } catch (Exception ex) {
            throw new Exception("Encryption exception: " + ex.getMessage());
        }
        user.setUserSecret(encryptedNewPassword);
        userRepository.save(user);
        log.debug("Changed password for User: {}", user);
    }
}
public void changePassword(String login、String currentClearTextPassword、String newPassword)引发异常{
//以可选方式获取用户
可选检查=userRepository.findOneByLogin(登录);
//如果用户存在“isPresent()”
if(检查.isPresent()){
//从可选窗口获取用户并执行您的操作
User=check.get();
字符串currentEncryptedPassword=user.getUserSecret();
字符串encryptedInputPassword=“”;
试一试{
encryptedInputPassword=authUtils.encrypt(currentClearTextPassword);
}捕获(例外情况除外){
抛出新异常(“加密异常:+ex.getMessage());
}
如果(!Objects.equals(encryptedInputPassword,currentEncryptedPassword)){

抛出新异常(“无效密码”);//就像@louis wasserman所说的,您可以使用未检查的异常

所以不是

throw new Exception("Invalid Password");
使用:


注意:最好使用适合您的用例的自定义RuntimeException。

对于一般情况,@pari ngang是正确的:在lambda表达式中,您不能在调用函数之外处理选中的异常。请使用未选中的或在lambda中使用
try
构造

但是,需要执行这两项操作之一可能是结构不良的标志。lambda中有一大块代码就是这样的标志之一。以下是针对您的具体情况的一些建议:

1。为了简化@ycf-l的答案,颠倒逻辑,如果找不到,只需返回
user

Optional<User> user = userRepository.findOneByLogin(login);
if (!user.isPresent()) {
    return;
}
// ... carry on as before outside of a lambda
3。您也可以使用类似的库来简化
try
/
catch
块:

String encryptedInputPassword = Try.of(() -> authUtils.encrypt(currentClearTextPassword))
    .onFailure(e -> System.err.println("Encryption exception: " + e.getMessage()))
    .orElse("");
4。如果您愿意追求vavr,您还可以解决更普遍的问题:

userRepository.findOneByLogin(login)
    .map(user -> Try.of(() -> {
        // Your change password stuff goes here.
        changePassword(user, currentClearTextPassword, newPassword);
        return null; // I don't currently know of any way of passing a runnable.
  }))
  // This pulls the exception out of the lambda function, satisfying the compiler.
  .orElseGet(() -> Try.success(null))
  .getOrElseThrow(Function.identity());

我没有太多使用vavr,因此无法告诉您这是否是vavr最有效/最干净的方法/使用,但它会解决您的问题。

您不能。要么使用未检查的异常,要么使用正常的
if(可选的.isPresent())
块,而不是
ifPresent
String encryptedInputPassword = Try.of(() -> authUtils.encrypt(currentClearTextPassword))
    .onFailure(e -> System.err.println("Encryption exception: " + e.getMessage()))
    .orElse("");
userRepository.findOneByLogin(login)
    .map(user -> Try.of(() -> {
        // Your change password stuff goes here.
        changePassword(user, currentClearTextPassword, newPassword);
        return null; // I don't currently know of any way of passing a runnable.
  }))
  // This pulls the exception out of the lambda function, satisfying the compiler.
  .orElseGet(() -> Try.success(null))
  .getOrElseThrow(Function.identity());