try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, IOException.class);
Throwables.propagateIfInstanceOf(t, SQLException.class);
throw Throwables.propagate(t);
}
Run Code Online (Sandbox Code Playgroud)
不是很具体.真正的程序会是什么样子?我真的不明白的方法的目的Throwables.propagateIfInstanceOf(Throwable, Class),propagate(),propagateIfPossible().我什么时候使用它们?
axt*_*avt 15
这些方法的目的是提供一种处理已检查异常的便捷方法.
Throwables.propagate()是对已经检查的异常包含在未经检查的异常中的常用习惯用法的简写(以避免在方法的throws子句中声明它).
Throwables.propagateIfInstanceOf()用于返回已检查的异常,如果它们的类型throws在方法的子句中声明的话.
换句话说,有问题的代码
public void doSomething()
throws IOException, SQLException {
try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, IOException.class);
Throwables.propagateIfInstanceOf(t, SQLException.class);
throw Throwables.propagate(t);
}
}
Run Code Online (Sandbox Code Playgroud)
是以下代码的简写:
public void doSomething()
throws IOException, SQLException {
try {
someMethodThatCouldThrowAnything();
} catch (IKnowWhatToDoWithThisException e) {
handle(e);
} catch (SQLException ex) {
throw ex;
} catch (IOException ex) {
throw ex;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
4289 次 |
| 最近记录: |