user674669
user674669

Reputation: 12352

Should I throw subtype of an Exception in the throws clause?

I am writing an API

void doSomething(args) throws Exception1, Exception2;

Exception1 is a subtype of Exception2.

Intellij idea is saying "There is a more general exception in the throws list already." I know java only requires me to have Exception2 in the throws clause but think I should have both in the throws clause for documentation purposes and to indicate to the caller that they can catch each one separately and do something different for each one. In my implementation of the API, I throw Exception1 and also calling an internal method which throws Exception2.

What is the recommended practice?

Thanks.

Upvotes: 2

Views: 961

Answers (3)

Oleg Estekhin
Oleg Estekhin

Reputation: 8395

You should write a javadoc that explains the conditions when each particular exception is thrown. Take a look at ReadableByteChannel.read() javadoc for example - the method declares only IOException in its throws clause, but describes a lot of more specific subclasses of that exception in its javadoc.

Upvotes: 6

keshlam
keshlam

Reputation: 8058

Catch can be more specific than what was nominally thrown, so there's no requirement to explicitly say that you're throwing both if one extends the other. No harm done in doing so either. There MAY be harm done in making one extend the other at all...

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79808

Just write throws Exception2 in your throws clause. The caller can still catch each of them individually, provided they put catch (Exception1 e) before catch (Exception2 e).

For example, FileNotFoundException is a subtype of IOException, and it is valid to write

try {
    doSomeStuff();
} catch (FileNotFoundException e) {
    System.out.println("There's no such file");
} catch (IOException e) {
    System.out.println("Your IO doesn't work");
}

even if doSomeStuff() is only declared as throwing IOException. But you can't do it the other way around. It's invalid to have the superclass's catch clause before the subclass's one.

Upvotes: 5

Related Questions