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.