on oracle ofiicial site write (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.
Please concentrate on second point (There are no other preceding catch blocks that can handle it
. )
Research following code:
static private void foo() throws FileNotFoundException {
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
throw e;
}
}
This code compiles good. According my opinion after reading quote from mentioned article I expect to see that compiler will verify it and I will get compiler error.
Did I understand second point wrong?
This is perfectly fine because the FileNotFoundException
is derived from IOException
, and because you go from less specific to a more specific there should not be any issues.
edit:
static private void foo() throws FileNotFoundException {
try {
throw new FileNotFoundException();
} catch (IOException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
throw e;
}
}