使用三元运算符引发已检查或未检查的异常

bla*_*234 7 java exception ternary-operator

用我原来的问题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();
}
Run Code Online (Sandbox Code Playgroud)

这也会编译(使用三元,2个未经检查的异常):

private void test3() { // throws not required
    throw new Random().nextInt(2)==0 ? new UncheckedIOException(null) : new RuntimeException();
}
Run Code Online (Sandbox Code Playgroud)

但是为什么不编译(使用三进制,1个选中的,1个未选中的)?

private void test2() throws IOException {
    throw new Random().nextInt(2)==0 ? new IOException() : new RuntimeException();
}
Run Code Online (Sandbox Code Playgroud)

从Eclipse:

未处理的异常类型Exception

2个快速修复可用:

J! 添加引发声明

J! 环绕尝试/捕捉


另一个例子

这样编译:

private void test4() { // throws not required
    if (new Random().nextInt(2)==0) throw new Error();
    throw new RuntimeException();
}
Run Code Online (Sandbox Code Playgroud)

这不是:

private void test5() {
    throw new Random().nextInt(2)==0 ? new Error() : new RuntimeException();
}
Run Code Online (Sandbox Code Playgroud)

从Eclipse:

未处理的异常类型Throwable

2个快速修复可用:

J! 添加引发声明

J! 环绕尝试/捕捉

Jon*_*eet 13

为什么不编译?

因为在这种情况下Exception,条件?:运算符的推断类型遵循JLS 15.25.3的规则。尽管JLS确实很快变得复杂,但是规则正在尝试找到“最具体的类型,其中两种操作数类型都有隐式转换”。一种“最近的共同祖先”。

在这种情况下,继承层次结构为:

                      Exception
                   /              \
           IOException           RuntimeException
               /                         \
      FileNotFoundException           IllegalStateException
Run Code Online (Sandbox Code Playgroud)

...因此最接近的共同祖先是Exception。您的代码等效于:

private void test() throws FileNotFoundException {
    Exception exception = 1==0 ? new FileNotFoundException() : new IllegalStateException();
    throw exception;
}
Run Code Online (Sandbox Code Playgroud)

希望你已经明白为什么会编译失败......在这种情况下,如果运气好的话这一切都清楚了吧:)

  • @PaulStelian是的。错误和运行时异常(以及子类)未被选中;其他检查。 (4认同)