I have two snippet of code :
class PreciseRethrow {
public static void main(String[] str) {
try {
foo();
} catch (NumberFormatException ife)
The difference is that the compiler can see that the only checked exception that can be rethrown in the first example is a NumberFormatException
. (You are not creating any new exceptions.) Therefore it is happy with the throws NumberFormatException {
declaration in the header.
In the second example however, you are explicitly throwing a checked exception that is not declared in the header, so predictably you get a compiler error.
Here ,You are throwing new Exception() from catch block but you have mentioned your method foo() can throw only NumberFormatException() which is lower in hierarchy
static private void foo() throws NumberFormatException {
try {
int i = Integer.parseInt("ten");
} catch (Exception e) {
throw new Exception();
}
}
The compiler can determine in the case of throw e
, that it can only be a checked exception of type NumberFormatException
which is already declared in the throws clause.
In the latter case you're trying to throw the checked Exception
which needs to be declared in the throws clause or caught.
In the first code snippet, you are re-throwing the NumberFormatException
that could possibly come up. In the second code snippet, you are throwing just general Exception
, which is not NumberFormatException
, as the method has declared.
You are attempting to throw an Exception, however you declare that you will throw a NumberFormatException
, which is a subtype of Exception
. All NumberFormatException
s are Exception
s, however not all Exception
s are NumberFormatException
, so it is not allowed. In the first example however, although you are catching an Exception
, the compiler and IDE know that it will only ever be a NumberFormatException
, which is safe.
In Both the case compile time error comes.Because you are try to throw a checked exception named Exception. You have to do one of two things:
use try construct in catch block OR add Exception in throws clause of foo()