1

assylias explain well about final rethrow. I added final to method3.

public void method4() throws IOException {
    try {
        throw new IOException("1");
    } catch (final Exception e) {
        e = new IOException("2"); //does not compile
        throw e; //does not compile
    }
}

I set my compiler to 1.7. method4 have two compile errors :

final exception can neither be reassigned nor throw precise exception. 

So, explicit final exception is only used to prevent modify?

Community
  • 1
  • 1
yuxh
  • 924
  • 1
  • 9
  • 23

1 Answers1

0

Exception of catch block is implicitly final that doesn't mean you can not reassign it. If you specifically make it final then compiler will not allow you to modify that reference. To make throw compile exception instance must be final or effectively final as already covered in linked answer.

public void method4() throws IOException {
    try {
        throw new IOException("1");
    } catch (final Exception e) {
        e = new IOException("2");// You can not modify final reference
        throw e;
    }
}

so explicit final exception is only used to prevent modify?

Yes exactly, in case of exception, final modifier is redundant. It is always recommended to throw or log the exception. Modification of any exception is an anti pattern according to me. Generally speaking even in case of custom exception we should not modify the thrown exception unless and until you have very strong reason to do so.

akash
  • 22,664
  • 11
  • 59
  • 87