Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception inside catch clause

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.

like image 442
user3528733 Avatar asked Apr 13 '14 10:04

user3528733


2 Answers

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...

like image 158
fge Avatar answered Oct 09 '22 18:10

fge


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.

like image 32
Keppil Avatar answered Oct 09 '22 18:10

Keppil