簡體   English   中英

嘗試拋出已檢查異常時出現編譯器錯誤

[英]Compiler error when trying to throw a checked exception

使用此代碼:

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

它如何在 lambda 內部拋出異常:(此代碼會引發編譯器錯誤)

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

來自 Java 庫的StoreTransactionalExecutable.java代碼:

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

我認為唯一的方法是讓 lambda 在 try/catch 中拋出一些RuntimeException並拋出以該RuntimeException作為原因的已檢查異常。 所以像:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM