我最初的问题使用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:
未处理的异常类型异常
有2个快速修复程序:
J!
添加引发声明
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!
添加引发声明
J!
围绕try / catch
答案 0 :(得分:13)
为什么不编译?
因为在这种情况下,条件?:运算符的推断类型为Exception
,遵循JLS 15.25.3的规则。尽管JLS确实很快变得复杂,但是规则正在尝试找到“最具体的类型,其中两种操作数类型都有隐式转换”。一种“最近的共同祖先”。
在这种情况下,继承层次结构是:
Exception
/ \
IOException RuntimeException
/ \
FileNotFoundException IllegalStateException
...因此最接近的共同祖先是Exception
。您的代码相当于:
private void test() throws FileNotFoundException {
Exception exception = 1==0 ? new FileNotFoundException() : new IllegalStateException();
throw exception;
}
希望您已经理解了为什么那个无法编译...在这种情况下,如果运气好的话,现在就很清楚了:)