我正在重构一些代码,以使用Guava Cache。
初始代码:
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);
}
}
}
有没有可能让它更好看一些呢?
throw new IllegalStateException(e);
这里是死代码行,只是为了让编译器高兴。 - Vadzim