exception parameter of uni-catch may be effectively final?

两盒软妹~` 提交于 2019-12-11 14:13:46

问题


A statement from Java doc.

An exception parameter of a uni-catch clause is never implicitly declared final, but may be effectively final.

What does may be implies here. Please explain with example.


回答1:


The JLS8 states in section 4.12.4:

A local variable or a method, constructor, lambda, or exception parameter is effectively final if it is not declared final but it never occurs as the left hand operand of an assignment operator (§15.26) or as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).

In the following example, the variable e is effective final. That means it can be used in lambda expressions and anonymous inner classes:

try {
    throw new RuntimeException("foobar");
} catch (RuntimeException e) {
    Runnable r = () -> { System.out.println(e); };
    r.run();
}

In the following example, the variable e is not effective final, because there is an assignment to that variable. That means, it can not be used within lambda expressions and anonymous inner classes:

try {
    throw new RuntimeException("foo");
} catch (RuntimeException e) {
    e = new RuntimeException("bar", e);
    Runnable r = () -> { System.out.println(e); }; // ERRROR
    r.run();
}


来源:https://stackoverflow.com/questions/22732039/exception-parameter-of-uni-catch-may-be-effectively-final

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!