Search code examples
javaexceptionchecked-exceptions

Declaring the same checked exception multiple times


I have just realized that I can write a method declaring the same checked exception several times.

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

I can't think of a reason why I would want to do this. I have been searching for a while but I am not being able to find if there is a resource that explains why is this acceptable or how could it be good. Can anyone point me to some resource about this?


Solution

  • There is nothing in the JLS that prevents you from specifying the same exception type (or even subtypes) in the throws clause. The only restriction, according to the JLS, Section 8.4.6, is:

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

    So, this compiles:

    throws RedundantException, RedundantException, RedundantException
    

    My IDE warns me of "duplicate throws", but it's not a compiler error.

    I see no good reason ever to do this. It has never occurred to me even to attempt this.

    This compiles, even if MySubclassException subclasses MyException:

    throws MyException, MySubclassException, MyException, MySubclassException
    

    The only reason I can think of to list subclass exception types in the throws clause is to document in your own Javadocs that the subclass may be thrown, so it can be handled separately.

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

    Even so, my IDE warns me of "a more general exception" in the list.

    Incidentally, it doesn't seem to matter whether any of the exception types in the examples above are checked.