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

huangapple go评论80阅读模式
英文:

Unreported exception must be caught or declared to be thrown:

问题

我有这段代码虽然它有Lombok的`SneakyThrows`注解但编译器仍然抱怨道:`错误:(65, 58java: 未报告的异常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&lt;Boolean&gt; unregister() throws RemoteException {
    if(registry != null) {
      Arrays.asList(registry.list()).forEach(className -&gt; {
        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(&quot;Database has not started&quot;);
    } 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&lt;Boolean&gt; unregister() {
       if (registry != null) {
           String[] classNames = registry.list();
           for(int i=0;i&lt;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

huangapple
  • 本文由 发表于 2020年10月22日 11:49:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64475029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定