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?