Fireburn
Fireburn

Reputation: 1021

Unreported exception must be caught or declared to be thrown:

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);
}

Upvotes: 3

Views: 3401

Answers (1)

dnault
dnault

Reputation: 8899

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

Upvotes: 2

Related Questions