英文:
Unreported exception must be caught or declared to be thrown:
问题
我有这段代码,虽然它有Lombok的`SneakyThrows`注解,但编译器仍然抱怨道:`错误:(65, 58)java: 未报告的异常java.rmi.RemoteException; 必须捕获或声明为抛出:`
```java
@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);
}
英文:
I have this code which although have the Lombok SneakyThrows
annotation, the compiler still complains that 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);
}
The method that calls this method above is this:
@SneakyThrows
public void stopDatabase() {
if(registrar == null) {
LOG.error("Database has not started");
} else {
registrar.unregister();
}
}
Updating the code to this (solves the issue)
but we don't want to change to using for-loop like this:
@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);
}
答案1
得分: 2
编译器报错是因为您告诉它unregister()
会抛出已检查的异常。从方法声明中删除throws RemoteException
,以便Lombok可以隐藏编译器对已检查异常的检查。
示例用法:https://projectlombok.org/features/SneakyThrows
英文:
The compiler is complaining because you're telling it unregister()
throws a checked exception. Remove the throws RemoteException
from the method declaration so Lombok can hide the checked exception from the compiler.
Example usage: https://projectlombok.org/features/SneakyThrows
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论