Throw exception inside catch clause

前端 未结 7 913
悲哀的现实
悲哀的现实 2021-01-12 15:34

I have two snippet of code :

class PreciseRethrow {
public static void main(String[] str) {
    try {
        foo();
    } catch (NumberFormatException ife)          


        
相关标签:
7条回答
  • 2021-01-12 16:34

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

    0 讨论(0)
提交回复
热议问题