Java Guava缓存和保留已检查异常
我正在重构一些代码以供使用 初始代码:Java Guava缓存和保留已检查异常,java,caching,exception-handling,guava,checked-exceptions,Java,Caching,Exception Handling,Guava,Checked Exceptions,我正在重构一些代码以供使用 初始代码: public Post getPost(Integer key) throws SQLException, IOException { return PostsDB.findPostByID(key); } 为了不破坏某些东西,我需要保留任何抛出的异常,而不包装它 目前的解决方案似乎有点难看: public Post getPost(final Integer key) throws SQLException, IOException {
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);
}
}
}
有什么方法可以让它变得更好吗?刚写完问题,就开始考虑使用泛型的实用方法。 然后我想起了一些关于他的事。 是的,它已经在那里了 可能还需要处理 因此,解决方案是:
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) {
Throwables.propagateIfPossible(
e.getCause(), SQLException.class, IOException.class);
throw new IllegalStateException(e);
} catch (UncheckedExecutionException e) {
Throwables.throwIfUnchecked(e.getCause());
throw new IllegalStateException(e);
}
}
非常好
另请参见和。只需使用Lombok的@Skillythrows即可。
强制异常包装不再有问题
现在是2021年,Java仍然检查异常。。。人们什么时候会发现,即使检查过的异常在纸上看起来不错,但在实践中却会产生太多的问题
长期解决方案:如果有机会,可以使用适当的语言,如Kotlin。
对于是否应该发布自我回答的问题犹豫不决。但这说明了一点:请注意,如果e.getCause是RuntimeException或错误,那么上面的代码将抛出该异常,而不是IllegalStateException。此答案中的代码与问题中的原始代码匹配,但是,如果出于某种奇怪的原因,您总是想将所有非SQL和非IO异常包装成一个非法状态异常,您将需要自定义代码。@Niraj,当然可以。抛出新的非法国家例外;这里有一行死代码只是为了让编译器高兴。