18
guava Cacheを使用するコードをリファクタリングしています。Guavaのキャッシュとチェックされた例外の保護
初期コード:
public Post getPost(Integer key) throws SQLException, IOException {
return PostsDB.findPostByID(key);
}
私があるとして、それをラップすることなく、任意のスローされた例外を維持するために必要な何かを破るしないために。
現在のソリューションは、やや醜い表示されます:
public Post getPost(final Integer key) throws SQLException, IOException {
try {
return cache.get(key, new Callable<Post>() {
@Override
public Post call() throws Exception {
return PostsDB.findPostByID(key);
}
});
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof SQLException) {
throw (SQLException) cause;
} else if (cause instanceof IOException) {
throw (IOException) cause;
} else if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new IllegalStateException(e);
}
}
}
は、それがよりよいようにするすべての可能な方法はありますか?
自己回答の質問を投稿する必要がある場合は躊躇します。しかし、これは明らかにした:http://meta.stackexchange.com/questions/2706/posting-and-answering-questions-you-have-already-found-the-answer-to – Vadzim
そして、ありがとう、guavaみんな! – Vadzim
** **有効回答;)と書いてください – Xaerxess