多次声明相同的检查异常

Declaring the same checked exception multiple times

我刚刚意识到我可以编写一个方法多次声明相同的检查异常。

public void myMethod() throws MyException, MyException, MyException {

我想不出我想要这样做的原因。我已经搜索了一段时间,但我无法找到是否有资源可以解释为什么这是可以接受的或者它怎么会好。谁能给我指点一些关于这方面的资源?

JLS 中没有任何内容可以阻止您在 throws 子句中指定相同的异常类型(甚至子类型)。根据 JLS, Section 8.4.6,唯一的限制是:

It is a compile-time error if an ExceptionType mentioned in a throws clause is not a subtype (§4.10) of Throwable.

所以,这个编译:

throws RedundantException, RedundantException, RedundantException

我的 IDE 警告我 "duplicate throws",但这不是编译器错误。

我看不出这样做有什么好的理由。我从来没有想过要尝试这个。

这编译,即使 MySubclassException 子类 MyException:

throws MyException, MySubclassException, MyException, MySubclassException

我能想到的在 throws 子句中列出子类异常类型的唯一原因是在您自己的 Javadocs 中记录子类可能会抛出,因此可以单独处理。

@throws MyException If something general went wrong.
@throws MySubclassException If something specific went wrong.

即便如此,我的 IDE 警告我列表中有 "a more general exception"。

顺便说一下,是否检查上面示例中的任何异常类型似乎并不重要。

中所述,重复的 throws 声明没有语义意义。但是,javac 仍然将它们记录在已编译的 class 文件中,使它们可用于反射,如下例所示:

public class Main {
    public static void main(String[] args) throws IOException, IOException,
            IOException, NoSuchMethodException {
        Arrays.stream(Main.class.getMethod("main", String[].class).getExceptionTypes())
                .forEachOrdered(System.out::println);
    }
}

打印

class java.io.IOException
class java.io.IOException
class java.io.IOException
class java.lang.NoSuchMethodException

这没有用(并且可能会暴露 Method.getExceptionTypes() 的错误消费者),但这是由重复的 throws 声明引起的行为差异。