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");
}
}
当我试图用?:
操作员改变它时,
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 功能(例如多捕获和类型化重新抛出)准备演示文稿时遇到了这段代码。有趣的。谢谢大家的这些好答案。我学到了很多。
更新
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?