r/javahelp • u/cowwoc • Sep 19 '24
A try-catch block breaks final variable declaration. Is this a compiler bug?
UPDATE: The correct answer to this question is https://mail.openjdk.org/pipermail/amber-dev/2024-July/008871.html
As others have noted, the Java compiler seems to dislike mixing try-catch blocks with final (or effectively final) variables:
Given this strawman example
public class Test
{
public static void main(String[] args)
{
int x;
try
{
x = Integer.parseInt("42");
}
catch (NumberFormatException e)
{
x = 42;
}
Runnable runnable = () -> System.out.println(x);
}
}The compiler complains:
Variable used in lambda expression should be final or effectively final
If you replace int x with final int x the compiler complains Variable 'x' might already have been assigned to.
In both cases, I believe the compiler is factually incorrect. If you encasulate the try-block in a method, the error goes away:
public class Test
{
public static void main(String[] args)
{
int x =
foo
();
Runnable runnable = () -> System.
out
.println(x);
}
public static int foo()
{
try
{
return Integer.
parseInt
("42");
}
catch (NumberFormatException e)
{
return 42;
}
}
}Am I missing something here? Does something at the bytecode level prevent the variable from being effectively final? Or is this a compiler bug?
0
u/VirtualAgentsAreDumb Sep 22 '24
What he meant to say is irrelevant. He used a flawed example, and the reason he thought that was relevant was because his flawed view on what the compiler can and can’t know.
Yes, but it was a bad example because it changed the core of the issue.
Not in that comment.
Yea, but this wasn’t covered in that comment.
In this sub thread that’s exactly what we are discussing. That was the core of the problem with the original comment, and the thing I pointed out in my first reply. Everything else in this sub thread is based on that.
Yes, so?
Why would that matter? I don’t care if other people are arguing the same point.
Again, why does that matter?