![](/img/trans.png)
[英]Configure Java Compiler for Error if method cannot throw declared checked Exception
[英]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.