关于java:在前面的catch块中处理的rethrowing异常

rethrowing exception handled in preceding catch block

在iIC站点上写入(http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html#rethrow)

In detail, in Java SE 7 and later, when you declare one or more
exception types in a catch clause, and rethrow the exception handled
by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

-The try block is able to throw it.

-There are no other preceding catch blocks that can handle it.

-It is a subtype or supertype of one of the catch clause's exception parameters.

请注意第二点(There are no other preceding catch blocks that can handle it)

研究以下代码:

1
2
3
4
5
6
7
8
9
static private void foo() throws FileNotFoundException  {
        try {
            throw new FileNotFoundException();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw e;
        }
    }

这段代码编译得很好。根据我的观点,在阅读了上述文章的引言后,我希望看到编译器会验证它,并且我会得到编译器错误。

第二点我理解错了吗?


这是非常好的,因为FileNotFoundException是从IOException衍生而来的,而且因为你从不太具体的到更具体的,所以不应该有任何问题。

编辑:

1
2
3
4
5
6
7
8
9
static private void foo() throws FileNotFoundException  {
    try {
        throw new FileNotFoundException();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        throw e;
    }
}


throw e;行实际上没有其他可以处理它的前面的catch块。的确,IOException可以是fileNotFoundException,但在这个特定的情况下不可以。如果是的话,它会被第一个捕获物捕获。