I have two snippet of code :
class PreciseRethrow {
public static void main(String[] str) {
    try {
        foo();
    } catch (NumberFormatException ife) {
        System.out.println(ife);
    }
}
static private void foo() throws NumberFormatException {
    try {
        int i = Integer.parseInt("ten");
    } catch (Exception e) {
        throw e;
    }
}
}
and :
class PreciseRethrow {
public static void main(String[] str) {
    try {
        foo();
    } catch (NumberFormatException ife) {
        System.out.println(ife);
    }
}
static private void foo() throws NumberFormatException {
    try {
        int i = Integer.parseInt("ten");
    } catch (Exception e) {
        throw new Exception();
    }
}
}
In second case I got compile error "Unhandled exception type Exception" when I throw new Exception () in catch clause. Can You explain me Why in first case everything is ok but in second i get compile error ? In both case I throw Exception but in second case i create new instance of exception (this in only difference beetwen this two examples). Thanks for help.
First of all: your first example does not compile with Java 6 either. It will however compile with Java 7 due to new features in exception handling.
See this link for more information. Basically, starting with Java 7, the compiler can analyze exceptions thrown form a try block more precisely; and even if you catch a superclass of one or more thrown exceptions and rethrow it "as is" (ie, without a cast), the compiler will not complain. Java 6 and earlier, however, will complain.
In your second example however you rethrow a new instance of Exception. And indeed, this does not match the signature.
All in all, it means that with Java 7, you can do that, but not with Java 6:
public void someMethod()
    throws MyException
{
    try {
        throw new MyException();
    } catch (Exception e) { // Note: Exception, not MyException
        throw e;
    }
}
Java 6 only sees that the catch parameter is of type Exception; and for Java 6, this does not match the method signature --> compile error.
Java 7 sees that the try block can only throw MyException. The method signature therefore matches --> no compile error.
But don't do this ;) It is rather confusing...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With