用于异常的java条件运算符

Jin*_*won 3 java

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试用?:操作员更改它时,

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");
}
Run Code Online (Sandbox Code Playgroud)

这是正常的吗?

谢意

当我准备Java 7功能的演示文稿时,我实际上遇到了这个代码,例如multiple-catch和typed rethrowal.有趣.谢谢大家的好消息.我学到了很多.

更新

Java 7已针对特定类型的重新抛出进行了改进,对吧?

void throwIoOrSql() throws IOException, SQLException {
}

void rethrowIoAndSql() throws IOException, SQLException {
    try {
        throwIoOrSql();
    } catch (Exception e) {
        throw e; // Ok with Java 7
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器无法看到那些明显的情况,这有点傻.

throw flag ? new IOException("io") : new SQLException("sql"); // obvious, isn't it?
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 10

是的,遗憾的是,编译器无法确定您是否可以抛出这两个异常中的一个(并且语言规范不要求它).

你在这里有一个三元运算符返回一个Exception.这可以是SQLException或者IOException,但是唯一常见的超类型Exception,这就是编译器在这里看到的内容.

Java中没有"联合类型".

与此案例相同:

 Object x = flag ? Integer.valueOf(1) : "a string";
Run Code Online (Sandbox Code Playgroud)

在这里,x也必须是一个Object,因为没有其他类型可以表达Integer || String.