未报告的异常必须被捕获或声明为抛出:

3

我有这样一段代码,虽然使用了Lombok的SneakyThrows注解,但编译器仍然报错:Error:(65, 58) java: unreported exception java.rmi.RemoteException; must be caught or declared to be thrown:

@SneakyThrows
@Override
public Optional<Boolean> unregister() throws RemoteException {
    if(registry != null) {
      Arrays.asList(registry.list()).forEach(className -> {
        registry.unbind(className);
      });
    }
    return Optional.of(true);
}

调用上述方法的方法如下所示:
@SneakyThrows
public void stopDatabase() {
    if(registrar == null) {
      LOG.error("Database has not started");
    } else {
      registrar.unregister();
    }
}

将代码更新为以下内容(解决问题) 但我们不想像这样改用for循环:

@SneakyThrows
@Override
public Optional<Boolean> unregister() {
       if (registry != null) {
           String[] classNames = registry.list();
           for(int i=0;i<classNames.length;i++) {
              registry.unbind(classNames[i]);
           }
      }
      return Optional.of(true);
}

调用unregister()方法的代码块是否需要使用try-catch语句或者声明throws RemoteException?请定义一下。 - undefined
尝试 @SneakyThrows (RemoteException.class) - undefined
@VietDD 调用 unregister 方法的方法也在其上添加了 SneakyThrows 注解 - undefined
在stopDatabase()函数中加入try catch怎么样?(将if {} else{}包裹起来) - undefined
因为 registrar.unregister(); 可能会抛出 RemoteException 异常,所以你需要捕获它或者再次将其抛给调用 stopDatabase() 方法的方法(至少有一个方法需要捕获 RemoteException 异常)。 - undefined
1个回答

2
编译器抱怨您告诉它unregister()会抛出已检查的异常。从方法声明中移除throws RemoteException,这样Lombok就可以将已检查的异常隐藏在编译器中了。
用法示例:https://projectlombok.org/features/SneakyThrows

1
此外,在阅读链接的网页时,请注意 SneakyThrows 的常见用途。它旨在使处理不必要的异常声明更加容易。RemoteException 不是一个不必要的异常,您应该处理它而不是试图隐藏它。Lombok 是编程工具中的强力武器。它绝不能交给未经训练的程序员使用。 - undefined
即使从声明中删除了异常,问题仍未解决。 - undefined
我想知道Lombok的集成是否正常工作。这里有一个设置指南:https://projectlombok.org/setup/overview - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接