Fireburn
Fireburn

Reputation: 1021

Compiler error when trying to throw a checked exception

With this code:

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

How can it throw an exception inside the lambda: (This code throws a compiler error)

Database database = Database.getInstance();
database.transactPersistentEntityStore(application.getDir(), 
    txn -> {
        // Compiler error:
        throw new Exception("Something wrong");
    });

StoreTransactionalExecutable.java code from a Java library:

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

Upvotes: 0

Views: 63

Answers (1)

pirho
pirho

Reputation: 12215

I think the only way is to let lambda throw some RuntimeException in a try/catch and throw the a checked exception having this RuntimeException as a cause. So something like:

try {
    database.transactPersistentEntityStore(application.getDir(), 
        txn -> {
            throw new RuntimeException("Something wrong");
        });
} catch (RuntimeException rte) {
    throw new SomeCheckedException(rte);
}

Upvotes: 2

Related Questions