【发布时间】:2019-09-26 17:31:43
【问题描述】:
考虑以下 try/catch 块:
try {
throwCheckedException();
} catch (IOException e) {
doStuffWithException(e);
}
在上面的块中,throwCheckedException 有机会抛出一个检查异常,所以我需要一个调用 doStuffWithException 的 catch 子句。但是,假设我想在此块中添加一条附加语句:
if (!someBoolean) {
throw new IOException("someBoolean must be true, got false.");
}
我应该使用 catch 块并将上面的代码简单地插入到 try 块中,还是复制 catch 块中的内容会更好,如下所示?
try {
throwCheckedException();
if (!someBoolean) {
doStuffWithException(
new IOException("someBoolean must be true, got false.")
);
}
} catch (IOException e) {
doStuffWithException(e);
}
【问题讨论】: