Try/Catch DU Exception
Tagir Valeev
amaembo at gmail.com
Sat Jul 13 04:50:35 UTC 2024
Hello!
This problem indeed bugs me and not only me. E.g., IntelliJ IDEA users
occasionally come and ask why we highlight such a variable as mutable:
https://youtrack.jetbrains.com/issue/IDEA-193255/Java-local-variable-highlighed-as-reassigned
https://youtrack.jetbrains.com/issue/IDEA-200048/Highlighting-for-reassigned-variables-exclude-variables-which-are-assigned-in-try-catch
If we support it, it should probably work for final fields initialization
in constructors as well.
With best regards,
Tagir Valeev
On Fri, Jul 12, 2024 at 10:24 PM Archie Cobbs <archie.cobbs at gmail.com>
wrote:
> I'd like to propose a very minor language improvement and would appreciate
> any feedback.
>
> This is a true corner case, but I bet most developers have tripped over it
> a few times. It's easy to work around... but still...
>
> Here's a simple example:
>
> void describeMyThread(Thread thread) {
> final String description;
> try {
> description = '"' + thread.getName() + "'";
> } catch (NullPointerException e) {
> description = "null";
> }
> System.out.println("the thread is " + description);
> }
>
> This doesn't compile:
>
> DUTest.java:8: error: variable description might already have been
> assigned
> description = "(null)";
> ^
>
> The error is a false positive: there is no way an exception can be thrown
> in the try block *after* description is assigned, because description
> being assigned is literally the last thing that occurs in the try block.
>
> Developers intuitively know that description will be DU at the start of
> the catch block, so the error feels surprising and makes the compiler seem
> less smart than it should be.
>
> My proposal is to fix this by adding a "try/catch DU exception" to
> §16.2.15:
>
> V is definitely unassigned before a catch block iff all of the following
> are true:
> V is definitely unassigned after the try block *or the try block ends
> with an assignment expression statement V=b and V is definitely unassigned
> after b*
> V is definitely unassigned before every return statement ...
>
> A prototype compiler implementation is here
> <https://github.com/openjdk/jdk/compare/master...archiecobbs:jdk:TryCatchDUException>
> .
>
> Thoughts?
>
> -Archie
>
> --
> Archie L. Cobbs
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240713/40f28fa6/attachment-0001.htm>
More information about the amber-dev
mailing list