简体   繁体   中英

Throwing exception inside lambda does not work

I'm having bit of a problem throwing exception inside a lambda, consider the following code:

public interface StoreTransactionalExecutable {
    void execute(@NotNull final StoreTransaction txn);
}

And a manager class:

public final class DatabaseManager {
  // ...
  @Override
  public void transactPersistentEntityStore(String dir, StoreTransactionalExecutable txn) {
    final PersistentEntityStore entityStore =
        getPersistentEntityStore(dir, isReadOnly);
    entityStore.executeInTransaction(txn);
  }
  // ...
}

When the manager class method transactPersistentEntityStore is accessed like this below, it works:

public class Service {
    databaseManager.transactPersistentEntityStore("/dbPath", txn -> {
         txn.find(); // do stuff (throws and works)
    });
}

However, if like this, it throws a compile-time error

public class Service {
    databaseManager.transactPersistentEntityStore("/dbPath", rethrow(
        transaction -> {
            StoreTransaction txn = (StoreTransaction) transaction; 
            txn.find(); // do stuff 
        }
     ));
}

Here's what's thrown

[ERROR]     method com.myproject.store.DatabaseManager.transactPersistentEntityStore(java.lang.String,jetbrains.exodus.entitystore.StoreTransactionalExecutable) is not applicable
[ERROR]       (argument mismatch; no instance(s) of type variable(s) T exist so that java.util.function.Consumer<T> conforms to jetbrains.exodus.entitystore.StoreTransactionalExecutable)
[ERROR]     method com.myproject.store.DatabaseManager.<T,B>transactPersistentEntityStore(java.lang.String,java.util.Map<java.lang.Class<T>,B>,jetbrains.exodus.entitystore.StoreTransactionalExecutable) is not applicable
[ERROR]       (cannot infer type-variable(s) T,B
[ERROR]         (actual and formal argument lists differ in length))

The code for the rethrow and ThrowingConsumer is this:

public final class Throwing {

  private Throwing() {}

  @Nonnull
  public static <T> Consumer<T> rethrow(@Nonnull final ThrowingConsumer<T> consumer) {
    return consumer;
  }

  @SuppressWarnings("unchecked")
  @Nonnull
  public static <E extends Throwable> void sneakyThrow(@Nonnull Throwable ex) throws E {
    throw (E) ex;
  }

}

and

@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T>{
  @Override
  default void accept(final T e) {
    try {
      accept0(e);
    } catch (Throwable ex) {
      Throwing.sneakyThrow(ex);
    }
  }
  void accept0(T t) throws Throwable;
}

I really wonder what could be wrong here? Any hints would be much appreciated.

About the first compiler error:
If you read the error carefully " argument mismatch ; no instance(s) of type variable(s) T exist so that java.util.function.Consumer conforms to jetbrains.exodus.entitystore.Sto reTransactionalExecutable"
You'll notice a few things:

  1. StoreTransactionalExecutable is not same as Consumer.
  2. StoreTransactionalExecutable is not a generic type. And Consumer is.
  3. StoreTransactionalExecutable doesn't extend consumer and has execute method not accept . So code inside entityStore.executeInTransaction(txn);calls execute method and not accept

So the compiler is complaining when you pass a Consumer object to transactPersistentEntityStore method.
Correct me if I am wrong.

One "sneaky" way to throw this (but with a try-catch) is to make a:

public class UncheckedException extends RuntimeException {
  public UncheckedException(Throwable cause) {
    super(cause);
  }
}

Then use like this:

class Scratch {
    public static void main(String[] args) {
        databaseManager.transactPersistentEntityStore("/dbPath", txn -> {
            try {
                somethingThatThrows();
            } catch (Exception e) {
                throw new UnchecekdServiceException(e);
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM