【发布时间】:2019-09-20 02:32:29
【问题描述】:
我最初的问题使用了FileNotFoundException 和IllegalStateException,因此它们包含在答案中。为了简单起见,我已将它们分别更改为它们的超类 IOException 和 RuntimeException。
这样编译(不使用三元,1 个选中,1 个未选中):
private void test() throws IOException { // throws is required
if (new Random().nextInt(2)==0) throw new IOException();
throw new RuntimeException();
}
这也可以编译(使用三元,2 个未经检查的异常):
private void test3() { // throws not required
throw new Random().nextInt(2)==0 ? new UncheckedIOException(null) : new RuntimeException();
}
但是为什么这不能编译(使用三元,1 个选中,1 个未选中)?
private void test2() throws IOException {
throw new Random().nextInt(2)==0 ? new IOException() : new RuntimeException();
}
来自 Eclipse:
未处理的异常类型Exception
提供 2 个快速修复:
J!添加 throws 声明
J!用 try/catch 包围
另外一对例子
这样编译:
private void test4() { // throws not required
if (new Random().nextInt(2)==0) throw new Error();
throw new RuntimeException();
}
这不是:
private void test5() {
throw new Random().nextInt(2)==0 ? new Error() : new RuntimeException();
}
来自 Eclipse:
未处理的异常类型 Throwable
提供 2 个快速修复:
J!添加 throws 声明
J!用 try/catch 包围
【问题讨论】:
-
@NathanHughes 条件评估为
boolean。整个三元表达式不需要求值相同的类型,System.out.println(a == b? "yes" : 5)就可以了。 -
@daniu 三元表达式被评估为
Object,这是最常见的超类型 -
关键是条件运算符不是if语句的简写。
标签: java exception ternary-operator