1

there are many question about java-7 feature "precise rethrow" and final Exception ex, i couldn't find clear answer for my question.

what is the relation between "precise rethrow" and final Exception ?

public static void main(String args[]) throws OpenException, CloseException {
    boolean flag = true;
    try {
        if (flag){
            throw new OpenException();
        }
        else {
            throw new CloseException();
        }
    }
    catch (final Exception e) {
        System.out.println(e.getMessage());
        throw e;
    } 
}

is that obligatory to use final keyword if i want to use "precise rethrow" ?

catch (final Exception e) {
    System.out.println(e.getMessage());
    throw e;
} 

if it is not obligatory can i reassign the ex reference to a new exception?

catch (Exception e) {
    System.out.println(e.getMessage());
    e=new AnotherException();
    throw e;
} 
Melad Basilius
  • 3,847
  • 10
  • 44
  • 81

1 Answers1

4

It is not required to declare the exception parameter (e in your examples) as final to get precise rethrow semantics. You will also get precise rethrow if the parameter is effectively final.

In your second example, the parameter is NOT effectively final so you don't get precise rethrow semantics.

(This even applies if the exception you assign to e is assignment compatible with the original exception thrown in the try block.)

Reference: JLS 11.2.2.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216