private static int testReturn(final boolean flag) {
return flag ? 1 : 2;
}
private static void testThrow1(final boolean flag)
throws IOException, SQLException {
if (flag) {
throw new IOException("IO");
} else {
throw new SQLException("SQL");
}
}
当我试图用?:
操作去改变它,Java条件操作例外
private static void testThrow2(final boolean flag)
throws
//IOException, SQLException, // not even required
Exception { // compiler wants this.
throw flag ? new IOException("IO") : new SQLException("SQL");
}
它是正常的吗?
谢意
当我正准备介绍了Java 7种的功能,如多副渔获物和类型rethrowal我居然遇到了这个代码。有趣。谢谢大家这些好的答案。我学到了很多。
更新
Java 7中已经为特定类型重新引发了改进,对不对?
void throwIoOrSql() throws IOException, SQLException {
}
void rethrowIoAndSql() throws IOException, SQLException {
try {
throwIoOrSql();
} catch (Exception e) {
throw e; // Ok with Java 7
}
}
这是有点愚蠢的编译器无法看到这些明显的情况。
throw flag ? new IOException("io") : new SQLException("sql"); // obvious, isn't it?